socket.io客户端没有收到

时间:2011-09-12 11:14:50

标签: node.js websocket express socket.io

我在nodejs中使用socket.io,我能够从客户端向服务器发送数据。但是当我从服务器发出时,客户端似乎没有收到这个... 我错过了什么?

服务器:

socket = io.listen(app);
socket.sockets.on('connection', function(client){ 
client.on('something-from-client', function(msg){
           console.log(msg);
       //do something.
       client.emit('some-result',{"total":docs.length});
   });
});

客户端:

var socket = io.connect('http://localhost:9999');
socket.on('some-result', function(data){
    console.log('received from server', data);
});
socket.emit("something-from-client",  {"lat":lat, "lng":lng});

1 个答案:

答案 0 :(得分:1)

确定它正常工作,如果正在使用express,则需要在服务器端进行一些小的更改

var port = 8111;
var server = express.createServer();
io = require('socket.io').listen(server);
server.listen(port);

io.sockets.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });
});

按照承诺 - 工作代码 - https://github.com/parj/node-websocket-demo/tree/socket_emit

CF参考 - http://socket.io/#how-to-use