socket.on('connection'...事件从未触发nodejs + express + socket.io

Gas*_*ton 12 websocket node.js express socket.io

问题 socket.io不工作

细节

  • 生成一个项目 express [folder]; cd [folder]; npm install;
  • 设置socket.io npm install socket.io
  • 使用以下代码运行节点应用程序
  • 客户端连接事件触发但服务器连接从未触发.

建立

  • 服务器 AWS Free Tier,Ubuntu 11.10,ami-a7f539ce
  • nodejs v0.6.5
  • 表达v2.5.1
  • socket.io v0.8.7

客户

 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');
 });
Run Code Online (Sandbox Code Playgroud)

服务器

 [...]

 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);           
 });
Run Code Online (Sandbox Code Playgroud)

为什么连接事件从未被触发?

Ric*_*asi 12

花了一段时间才注意到... connection事件已经开始了io.sockets.在你的代码中,这将是

socket.sockets.on('connection', function (client) {
  client.send("hello")
  console.log("hello", client)
})
Run Code Online (Sandbox Code Playgroud)

您应该使用io而不是socketvar名称来避免这种混淆.