我尝试在房间之间发送一些消息。我有:
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
如果此代码正常工作,则应记录如下:
>> 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);
它们都不起作用。我想念一下吗?
感谢。
答案 0 :(得分:0)
我没有浏览你的所有代码,但一般的想法是你想在发送消息时从客户端发出事件+数据,然后在服务器端设置一个事件来广播什么时候发生。下面的一些伪服务器端代码:
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 };