6

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

Jeroen
  • 557
  • 1
  • 7
  • 15

1 Answers1

1

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.

EhevuTov
  • 20,205
  • 16
  • 66
  • 71
  • When I try to add socket.io.js into my client, I get an error that the client can't find "require". I looked at the socket.io.js code and it uses require, which I thought was a server side (ie, node) thing only, not a JavaScript in the browser supported thing. Is there another library that we need to include in the client that implements a client-side "require"? or am I missing something? – Elisabeth Feb 14 '12 at 04:23
  • @Elisabeth you should make that into a new question. You won't be using require() in the client. In the client, you'll use – EhevuTov Feb 14 '12 at 04:49
  • I figured it out; it was that you must serve the client code using the socket.io server so it can do some magic on the client code. – Elisabeth Feb 24 '12 at 00:14