Socket.io播放不工作

我有以下代码:

var room = "1"; var chat = io.connect("localhost:3700/"); self.chat = chat; chat.on("connection", function(socket){ socket.emit("room", room); socket.on('message', function (data) { self.receiveMessage(data); }); }); chat.broadcast.to(room).emit('send',"HEllo"); 

receiveMessage:

 receiveMessage: function(data){ var $elem = $("#chat1"); var $content = $elem.find(".messageText"); if(data.message) { messages.push(data); var html = ''; for(var i=0; i<messages.length; i++) { html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>'; html += messages[i].message + '<br />'; } $content.html(html); } else { console.log("There is a problem:", data); } } 

chat.broadcast.to(room).emit('send',"HEllo"); 给我的错误:

Uncaught TypeError:不能调用未定义的方法

我究竟做错了什么?

       

网上收集的解决方案 "Socket.io播放不工作"

不太确定,但我认为你只能通过连接发送广播。

你可以试试这个:

 var room = "1"; var chat = io.connect("localhost:3700/"); self.chat = chat; chat.on("connection", function(socket){ socket.emit("room", room); socket.on('message', function (data) { self.receiveMessage(data); }); chat.broadcast.to(room).emit('send',"HEllo"); }); 

当然,你也可以在一个单独的处理程序中发送广播,即:

 var room = "1"; var chat = io.connect("localhost:3700/"); self.chat = chat; chat.on("connection", function(socket){ socket.emit("room", room); socket.on('message', function (data) { self.receiveMessage(data); }); socket.on('foo event', function(data) { chat.broadcast.to(room).emit('send',"HEllo"); } });