Reputation: 10496
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?
Upvotes: 1
Views: 1946
Reputation: 122
Try putting both var socket = io.connect('http://localhost:8080/abc'); and socket.on('something', function(data) in the same script tag.
(Essentially try making your whole script in one HTML element, instead of separating them.)
Upvotes: 0