In the following code snippet(using node.js and socket.io library), sometimes (and sometimes not) server emit event something
before client side set up socket listener for something
event which will cause that associated anonymous function will not execute.
Client-side: index.html
<script src="socket.io/socket.io.js"></script>
<script>
...
var socket = io.connect('http://localhost:8080/abc');
...
</script>
<script src="/somewhere/test.js"></script>
Content of test.js
...
console.log(new Date().getTime(), 'debugging');
socket.on('something', function(data) {
// will not execute
console.log(data);
});
...
Server-side:
io.of('/abc').on('connection', function(socket) {
console.log(new Date().getTime(), 'EMIT SOMETHING');
io.of('/abc').emit('something', 'b');
});
Result of console.log on the client side: 1439057954676 debugging
Result of console.log on the server side: 1439057954114 EMIT SOMETHING
Why server emit event before client set up listeners in the above example?
Copyright Notice:Content Author:「Srle」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/31897363/socket-io-server-emit-event-before-client-set-up-listener-for-that-event