socket.on('connection' … event never fired

2019-02-06 08:57发布

Problem socket.io NOT working

Details

  • Generated a project with express [folder]; cd [folder]; npm install;
  • Setup socket.io npm install socket.io
  • Run node app with below code
  • Client connect event fires but server connection NEVER fired.

Setup

  • Server AWS Free Tier, Ubuntu 11.10, ami-a7f539ce
  • nodejs v0.6.5
  • express v2.5.1
  • socket.io v0.8.7

Client

 var socket = io.connect('http://example.com:3000');

 socket.on('connect', function() { 
    console.log('connected');
 });

 socket.on('message', function(msg){
    console.log(msg);
 });

 socket.on('disconnect', function() {
    console.log('disconnected');
 });

 socket.on('error', function (e) {
    console.log('System', e ? e : 'A unknown error occurred');
 });

Server

 [...]

 app.listen(3000);

 // socket.io setup
 var socket = require('socket.io').listen(app);

 // socket.io connection establishment
 socket.on('connection', function (client) {
    client.send("hello");
    console.log("hello", client);           
 });

Why is connection event never fired?

3条回答
来,给爷笑一个
2楼-- · 2019-02-06 09:24

Ricardo Tomasi is correct, saved my life, i was going crazy.

Altough things changed, we are in 2013, there's still an issue opened (since 2 years) on this

probably something changed, anyway to register the 'connect' event i had to do this:

var openSocket = function (uniqueID) {
  var appSocket = io.connect('/'+uniqueID, { transports: ['websocket', 'xhr-polling']});
  appSocket.socket.on('connect', function () {
    console.log('i did connect.');
  });
  return appSocket;
};
查看更多
女痞
3楼-- · 2019-02-06 09:46

Took a while to notice... the connection event is emmited on io.sockets. In your code this would be

socket.sockets.on('connection', function (client) {
  client.send("hello")
  console.log("hello", client)
})

You should use io instead of socket as the var name to avoid this confusion.

查看更多
Rolldiameter
4楼-- · 2019-02-06 09:48

The following did a trick for me with: socket.io-client: "^0.9.16"

io.connect("http://localhost:4000", {'force new connection': true});

Now 'connect' event fires consistently and there is no re-use.

I figured out this option by examining socket.io-client/lib/io.js line: 192 Since I can't even find this io.js file in github, I think there is refactoring in future releases, and this option might not work.

At least this might be helpful to somebody who will take this temporary work around.

查看更多
登录 后发表回答