Ad

Socket.io Not Emitting Event From Server To Client On Connection

- 1 answer

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?

Ad

Answer

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>
Ad
source: stackoverflow.com
Ad