简体   繁体   中英

socket.io client not receiving

I am using socket.io in nodejs and I am able to send data from client to server. But when I emit from server, the client does not seem to be receiving this... What am i missing ?

server:

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});
   });
});

client:

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});

Ok got it working, if express is being used, some minor changes need to be done on server side

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);
    });
});

As promised - Working code - https://github.com/parj/node-websocket-demo/tree/socket_emit

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM