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));
});
});
爲什麼這個代碼不起作用?我該怎麼辦,發送消息到不同的房間?