socket.io实现一个简单的聊天

我试图在socket.io谷歌组问,但没有人可以(或不想)帮助我。

我在服务器端有这段代码:

var chat = io .of('/chat') .on('connection', function (socket) { socket.emit('message', { that: 'only' , '/chat': 'will get' }); }); chat.on("message", function(data){ console.log(data); }); 

而在客户端我有这样的代码:

  var chat = io.connect('http://localhost/chat'); chat.on('message', function (data) { chat.emit('hi!'); }); chat.emit("message", {"this": "is a message"}); 

在控制台上,我可以看到从服务器发送的第一条消息,但它似乎是客户端,一旦连接并收到消息,不会发出'hi!' 信息。 而且我想让客户也发出另一条消息,即我贴的最后一行。 另外这个消息不被服务器接收(理论上它应该logging它)。

我肯定会做错事,谁能指出这到底发生了什么? 我最终想要实现的只是build立一个简单的类似聊天的系统,但是我希望这些东西(频道)在实际上写聊天之前就工作。 谢谢

不发送“hi”的原因是因为.emit的第一个参数是事件名称,在这里它是“hi”。 从技术上讲,如果你在服务器端进行以下操作,我认为你应该得到一个未定义的数据(因为你没有把第二个参数作为要发送的对象):

 .on('hi',function(data){ console.log(data) // should log "undefined" }); 

您也可以使用.send ,它就像web-sockets语义一样, .send送到message事件。 如果你把.emit .send在客户端,它应该可以工作。

综上所述:

 .emit('eventName', 'data') // sends to the eventName name .send('data') // sends to message event 

工作客户端代码:

  var chat = io.connect('http://localhost/chat'); chat.on('message', function (data) { chat.send('hi!'); }); chat.emit("message", {"this": "is a message"}); 

我把它弄糊涂了一点,但是:

服务器:

 var io = require('socket.io').listen(8080); var chat = io .of('/chat') .on('connection', function (socket) { socket.send('welcome to the interwebs'); socket.on('message', function(data) { console.log(data); }); }); 

客户:

 <html> <body> <script src="http://10.120.28.201:8080/socket.io/socket.io.js"></script> <script type="text/javascript"> var chat = io.connect('http://10.120.28.201:8080/chat'); chat.on('connect', function () { console.log("connected"); chat.send('hi!'); chat.on('message', function (data) { console.log(data); }); }); </script> </body> </html>