跨室通讯难题

我尝试在房间间发送一些消息。 我有:

server.js

var io = require('socket.io').listen(8081); var chat = io .of('/chat') .on('connection', function (socket) { socket.on('chatTestEmit1', function(d) { console.log('>> chatTestEmit1 >> '+JSON.stringify(d)); console.log(io.sockets.manager.rooms); socket.to('/news').emit('newsTestEmit1', d); }); }); var news = io .of('/news') .on('connection', function (socket) { socket.on('checkAlive', function(d) { console.log('>> checkAlive >> '+JSON.stringify(d)); }); socket.on('newsTestEmit1', function(d){ console.log('>> newsTestEmit1 >> '+JSON.stringify(d)); }); }); 

client.html

 <script src="http://localhost:8081/socket.io/socket.io.js"></script> <script> var chat = io.connect('http://localhost:8081/chat') , news = io.connect('http://localhost:8081/news'); chat.on('connect', function () { chat.emit('chatTestEmit1',{msg:'This is the message from client.'}); }); news.on('connect', function(){ news.emit('checkAlive',{msg:'News is alive'}); }); </script> 

日志看起来像这样:

  info - socket.io started debug - client authorized info - handshake authorized 74858017692628057 debug - setting request GET /socket.io/1/websocket/74858017692628057 debug - set heartbeat interval for client 74858017692628057 debug - client authorized for debug - websocket writing 1:: debug - client authorized for /chat debug - websocket writing 1::/chat debug - client authorized for /news debug - websocket writing 1::/news >> chatTestEmit1 >> {"msg":"This is the message from client."} { '': [ '74858017692628057' ], '/chat': [ '74858017692628057' ], '/news': [ '74858017692628057' ] } debug - websocket writing 5::/chat:{"name":"newsTestEmit1","args":[{"msg":"This is the message from client."}]} >> checkAlive >> {"msg":"News is alive"} debug - emitting heartbeat for client 74858017692628057 debug - websocket writing 2:: debug - set heartbeat timeout for client 74858017692628057 debug - got heartbeat packet debug - cleared heartbeat timeout for client 74858017692628057 debug - set heartbeat interval for client 74858017692628057 debug - emitting heartbeat for client 74858017692628057 

如果这段代码正常工作,它应该logging如下:

 >> newsTestEmit1 >> {"msg":"This is the message from client."} 

出现在日志中。 请注意,我也试过:

 io.sockets.in('/news').emit('newsTestEmit1', d); io.sockets.in('news').emit('newsTestEmit1', d); io.of('/news').emit('newsTestEmit1', d); 

他们都没有工作。 我想念什么?

谢谢。

我并没有浏览所有的代码,但总体思路是,当发送消息时,你想从客户端发送一个事件+数据,然后在服务器端设置一个事件,以便在发生时进行广播。 下面的一些伪服务器端代码:

 io.sockets.on('connection', function (socket) { console.log('Socket connection established.'); socket.on('message event', function(data){ socket.broadcast.emit('global chat update', data);} ); }); 

在客户端,你需要2位代码:

1)当聊天事件发生时,如:

 socket.emit('message event', data) 

2)有一个全球聊天更新时显示最新的聊天。

 socket.on('global chat update', function(data) { // your script to update chat data here };