简体   繁体   中英

socket.io not emitting event from server to client on connection

I have a very basic setup with socket.io but am having trouble getting my server to send back a message once the connection has been established.

When a connection is established to my server, I want the server to send back a message to the client. I've tried to accomplish this with the following code:

Server

// Modules
var fs = require('fs');
var https = require('https');

// Certificate
var options = {
    pfx: fs.readFileSync('<my cert>')
};


// Create Server
httpsServer = https.createServer(options);

// Create websocket
var io = require('socket.io')(httpsServer);

// Listen on a port
httpsServer.listen(4000,function() {
    console.log('listening on *:4000');
});

io.on('connection', function(socket) {
    console.log('a user connected');
    socket.emit('test','you connected');
});

Client

var socket = io('https://<my server>:4000');

When I execute this code, the websocket gets established and my server console shows the message "a user connected" . However, the message ['test','you connected'] does not get emitted through the socket.

The only way I've been able to get this to work is to use setTimeout() to wait 500ms before emitting the event, in which case it does work.

Why is that? How can I configure my server to automatically respond with a message as soon as the user connects?

You need to listen to the emitted event, using socket.on(event, callback);

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

<script>
    var socket = io('https://localhost:4000');
    //test is the emitted event.
    socket.on("test", function(data){
      console.log(data); //"you connected"
    });
</script>

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