Why don't I see a response from socket.io-clie

2019-06-06 04:35发布

问题:

var io = require('socket.io-client'),
    socket = io.connect('targeturl', {
        port: 8080
    });
socket.on('connect', function () {
    console.log("socket connected"); //this is printed.
    });
socket.emit('list', {"user":'username',"token": 'mytoken'});
socket.on('message', function(data){
    console.log(data);
});

socket.on('error', function(data){
    console.log(data); //nothing is printed
});

I see the message 'socket connected' when running this from node.js on the command line but I don't see a response from the 'list' call.

Note that this is a specific question about using socket-io-client from Node.js as a command line application.

I have verified using curl that I can reach the socket server which is REMOTE i.e I do not have the server code but I know that it uses socket.io.

回答1:

I'm no expert on the matter, but it appears you're attempting to emit the message before the connection is established. (This stuff is asynchronous after all.)

Try moving the emit call inside of the handler for the 'connect' event, to ensure that it happens afterward.