.emit()延迟时混淆socket.io行为

时间:2014-04-01 17:59:00

标签: node.js ubuntu socket.io

有一些令人困惑的套接字/异步行为,我真的可以使用一些帮助理解。

这是我的(人为的)服务器代码:

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);

server.listen(3003);

app.get('/', function (req, res) {
    res.sendfile("index.html");
    app.use(express.static(__dirname));
});

var room = "random";
var room2 = "another_room";

function make_socket_emit(socket, msg, timeout) {
  setTimeout(function() {
    socket.emit("message", msg);      
  }, timeout);
}

io.sockets.on("connection", function(socket) {
  socket.join(room);

  make_socket_emit(io.sockets.in(room2), "Ni!", 500);

  make_socket_emit(io.sockets.in(room), "I have been imprisoned by my father, who wishes me to marry against my will.  Please, please, please come and rescue me.", 500);
});

这是HTML:

<!DOCTYPE html>
<html>
   <head>
      <title>Test Instantiation Delay and Room Issue</title>
      <script src="socket.io/socket.io.js"></script>
   </head>
<body>

</body>
<script>
var socket = io.connect('http://localhost:3003');

socket.on('connect', function() {
    console.log('Connected');

    socket.on("message", function(msg) {
      console.log("Message for you, sir!:", msg);
    });
});
</script>
</html>

我只期待这个房间&#39;要发送的消息,但都会被发送。

如果切换&#39; make_socket_emit&#39;的顺序在我的机器上只接收到到room2的消息。

非常感谢,

0 个答案:

没有答案