简体   繁体   English

使用node.js和socket.io向客户端发送信息时出现延迟

[英]Delay when sending information to client using node.js and socket.io

I have an application written in node.js with a timer function. 我有一个用node.js编写的应用程序,带有一个计时器功能。 Whenever a second has passed, the server sends the new time value to every connected client. 只要一秒钟过去,服务器就会将新的时间值发送给每个连接的客户端。 While this works perfectly fine on localhost, it's very choppy when hosted online. 虽然这在localhost上完全正常,但在线托管时却非常不稳定。 Clients won't update immediately and the value will sometimes jump two or three seconds at a time. 客户端不会立即更新,有时每次跳转两到三秒。

I discovered, however, if I repeatedly send the timer data to the clients (using setInterval), it runs perfectly without any delay from anywhere. 但是,我发现,如果我反复将定时器数据发送到客户端(使用setInterval),它可以完美地运行,而不会有任何延迟。

Does anyone have any idea why this might be the case? 有谁知道为什么会出现这种情况? It doesn't make sense to me why sending the same data more often would fix the issue. 对我来说,为什么更频繁地发送相同数据会解决问题是没有意义的。 If anything, shouldn't this be more slow? 如果有的话,这不应该更慢吗? I was thinking I could use this approach and have the client notify the server when it has updated but this seems unnecessary and inefficient. 我以为我可以使用这种方法并让客户端在更新时通知服务器,但这似乎是不必要和低效的。

I'm very new to node.js but this has got me stumped. 我对node.js很新,但这让我很难过。 Any insight would be greatly appreciated. 任何见解将不胜感激。

Where are you hosting it? 你在哪里托管它? Does it support websockets? 它支持websockets吗? Some hosts do not support/allow them. 有些主机不支持/允许它们。 My guess is that your host is not allowing websockets and socket.io is falling back to the polling transport. 我的猜测是你的主机不允许websockets和socket.io回到轮询传输。

In your browser, you can find the websocket connection and inspect it in developer tools: How do you inspect websocket traffic with Chrome Developer Tools? 在浏览器中,您可以找到websocket连接并在开发人员工具中进行检查如何使用Chrome开发人员工具检查websocket流量?

If it does not undergo the 101 Switching Protocols http status to successfully upgrade the first request to a websocket, you'll see the polling requests recur in the developer tools. 如果它没有经过101 Switching Protocols http状态以成功将第一个请求升级到websocket,您将看到在开发人员工具中重复出现轮询请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM