I've got a node.js server up and running with express and i'm trying to establish a websocket connection using socket.io server-side and chrome 12 client-side. When I try to connect, socket.io outputs a debug message saying "destroying non-socket.io upgrade" and the code in my connection handler doesn't run. Also on the client-side the readyState of my socket is 2 (CLOSING).
[edit] readyState of the socket changed from 0 to 2
The most common cause of Websocket error is when you connect to DSS through a proxy. Websockets is a fairly recent protocol and many enterprise proxies do not support it. The websocket connection will not establish and you will see this message.
Node. js can maintain many hundreds of WebSockets connections simultaneously. WebSockets on the server can become complicated as the connection upgrade from HTTP to WebSockets requires handling.
Make sure you're inserting the socket.io.js file into your client code and using it. If you try to create your own websocket on the client-side, you'll probably run into problems.
Do something like this for your server:
var app = require('express').createServer()
, io = require('socket.io').listen(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
and something like this for the HTML file you're serving:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Make sure you're serving /socket.io/socket.io.js
from your webserver dir. Then all you have to do is watch your console log in the web browser's Developer environment from the Options or with Firebug when you go to the page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With