0
我是node.js和socket.io的新手,在官方socket.io网站的'开始'代码之后,我写了简单的聊天。然后,我想创建不同的房间,就像在使者中一样。但是依靠官方文档,我不能这样做,因为我自己...... 这里是我的服务器代码:socket.io中的房间。如何发送消息?
io.on('connection', function(socket) {
var room_name = socket.request.headers.referer; // link of the page, where user connected to socket
// connecting to room
socket.join(room_name, function(){
//trying to send messages to the current room
io.to(room_name, function() {
socket.on('chat message', function (msg) {
io.emit('chat message', msg);
});
});
});
});
而且我客户端代码:
$(function() {
var socket = io();
//when we submit our form
$('form').submit(function(){
//we are sending data to socket.io on server
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
//And then we are creating message in our html code
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
为什么这个代码不起作用?我该怎么办,发送消息到不同的房间?