带有 Socket.IO 延迟发射数据的 NodeJS [英] NodeJS with Socket.IO delay emitting data

查看:20
本文介绍了带有 Socket.IO 延迟发射数据的 NodeJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Socket.IO 主页 (http://socket.io/) 中的示例.它可以正常工作,但在发送数据和另一端接收数据之间存在巨大延迟.

I am using the example from the Socket.IO homepage (http://socket.io/). It works and everything, but there is a huge delay between the time data is sent, and when that data is received on the other end.

我正在使用 XAMPP,我的目录中有 socket.html,并在浏览器中使用http://localhost/socket.html"导航到它,并且我让服务器侦听端口 8080.

I am using XAMPP, I have socket.html in my dir, and navigate to it using "http://localhost/socket.html" in my browser, and I have the server listening on port 8080.

服务器:

var io = require('socket.io').listen(8080);

io.sockets.on('connection', function (socket) {
 socket.emit('news', { hello: 'world' });
 socket.on('my other event', function (data) {
   console.log(data);
 });
});

HTML 文件:

<html>
<head>
    <script src="http://localhost:8080/socket.io/socket.io.js"></script>
    <script>
      var socket = io.connect('http://localhost:8080');
      socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
      });
    </script>
</head>

<body>

</body>
</html>

推荐答案

我发现了问题.

在服务器中我改了:

var io = require('socket.io').listen(8080);

var io = require('socket.io', { rememberTransport: false, transports: ['WebSocket', 'Flash Socket', 'AJAX long-polling'] }).listen(8080);

强制服务器使用 WebSockets、Flash Sockets 或长轮询.它将尝试按该顺序使用它们.rememberTransport 强制服务器和客户端忘记上次使用的连接,并尝试与上面的传输"连接.

which forces the server to use either WebSockets, Flash Sockets, or long-polling. It wil try to use those in that order. The rememberTransport forces the server and client to forget which connection it used last, and try to connect with the 'transports' above.

在客户端,我几乎做了同样的事情.我补充说:

On the client side I just pretty much did the same thing. I added:

{ rememberTransport: false, transports: ['WebSocket', 'Flash Socket', 'AJAX long-polling']}

到套接字构造函数.所以它看起来像:

to the socket constructor. So it looked like:

var socket = io.connect('http://localhost:843', { rememberTransport: false, transports: ['WebSocket', 'Flash Socket', 'AJAX long-polling']});

现在它似乎完美运行.

谢谢各位.

这篇关于带有 Socket.IO 延迟发射数据的 NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆