在下面的代码段(使用node.js和socket.io库)中,有时(有时不)服务器会在客户端为<code>something</code>事件设置套接字侦听器之前发出事件<code>,这将导致相关的匿名函数无法执行。
客户端:索引.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>
test. js的内容
...
console.log(new Date().getTime(), 'debugging');
socket.on('something', function(data) {
// will not execute
console.log(data);
});
...
服务器端:
io.of('/abc').on('connection', function(socket) {
console.log(new Date().getTime(), 'EMIT SOMETHING');
io.of('/abc').emit('something', 'b');
});
客户端console.log的结果:< code>1439057954676调试
服务器端console.log的结果:< code>1439057954114发出一些东西
在上面的例子中,为什么服务器在客户端设置侦听器之前发出事件?
尝试将var socket = io . connect(' http://localhost:8080/ABC ');和socket.on('something ',function(data)在同一个脚本标签中。< br >(基本上,尝试将整个脚本放在一个HTML元素中,而不是将它们分开。)