socket.io的房间。如何发送消息?

时间:2017-03-15 23:38:29

标签: javascript node.js websocket socket.io

我是node.js和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));
            });
        });

为什么这段代码无法运作?我可以做什么,将信息发送到不同的房间?

1 个答案:

答案 0 :(得分:0)

将其添加到服务器代码:

 var room_name = socket.request.headers.referer; // link of page, where user connected to socket

     //connecting to room
 socket.join(room_name);
 socket.on('chat message', function (msg) {
     io.to(room_name).emit('chat message', msg);
 });