Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

websocket problem: cannot connect to node.js server

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

like image 284
Jeroen Avatar asked Jul 09 '11 13:07

Jeroen


People also ask

What causes WebSocket connection error?

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.

Does node js support WebSockets?

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.


Video Answer


1 Answers

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.

like image 180
EhevuTov Avatar answered Sep 30 '22 18:09

EhevuTov