socket.on('connection' ... 事件从未触发 nodejs + express + socket.io [英] socket.on('connection' ... event never fired nodejs + express + socket.io

查看:28
本文介绍了socket.on('connection' ... 事件从未触发 nodejs + express + socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题 socket.io 不工作

Problem socket.io NOT working

详情

  • express [文件夹]生成一个项目;cd [文件夹];npm 安装;
  • 设置socket.io npm install socket.io
  • 使用以下代码运行节点应用
  • 客户端 connect 事件触发,但服务器 connection 从未触发.
  • 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.

设置

  • 服务器AWS 免费套餐,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');
 });

服务器

 [...]

 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);           
 });

为什么 connection 事件从不触发?

Why is connection event never fired?

推荐答案

花了一段时间才注意到... connection 事件是在 io.sockets 上发出的.在您的代码中,这将是

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)
})

您应该使用 io 而不是 socket 作为 var 名称以避免这种混淆.

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

这篇关于socket.on('connection' ... 事件从未触发 nodejs + express + socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆