为什么我的 socket.io 使用长轮询而不是 websocket? [英] Why is my socket.io using long polling instead of the websocket?

查看:67
本文介绍了为什么我的 socket.io 使用长轮询而不是 websocket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我用 NodeJS + ExpressJS 服务器设置了 socket.io,一切都运行良好.唯一的问题是我刚刚意识到我的 emit() 调用正在使用回退 XHR 方法将事件发送到我的服务器,而不是它打开的 websocket 连接.

So I set up socket.io with a NodeJS + ExpressJS server and everything is working well. The only problem is I just realized that my emit() calls are using the fallback XHR method to send the event to my server rather than the websocket connection it has open.

当我查看连接时,我看到的只是一些 2probe3probe,然后是一堆通过 websocket 发送的 2 和 3.此连接似乎已打开并且可以正常工作,那么为什么它会退回到带有 XHR 请求的长轮询?

When I view the connection, all I see are some 2probe, 3probe, followed by a bunch of 2's and 3's being sent across the websocket. This connection appears to be open and working, so why is it falling back to long polling with XHR requests?

我现在没有提供任何代码,因为我不确定哪一部分是相关的,因为代码的功能方面运行良好,我只想通过 XHR 使用 websocket.如果有任何您想看的代码,请告诉我

I am not providing any code right now because I am not sure what part would be relevant since the functional aspect of the code is working great, I just want to utilize the websocket over XHR. Let me know if there is any code you would like to see

更新

所以我对套接字进行了更多测试,并添加了几个 emit() 调用.看起来第一个 1 或 2 个发出使用长轮询,然后突然间它更改为使用 websocket.只是好奇这里发生了什么.

So I was testing out the sockets a little more and I added a couple more emit() calls. It appears like the very first 1 or 2 emits use the long polling and then all of a sudden it changes over to using the websocket. Just curious what is happening here.

推荐答案

从 Socket.IO 1.x 开始,回退算法从降级方法变为升级方法.

Since Socket.IO 1.x, the fallback algorithm changed from a downgrade approach to an upgrade approach.

长轮询几乎适用于任何地方,因此首先使用它,以便您可以立即获得连接".然后在后台尝试将长轮询连接升级为 websocket 连接.如果升级成功,长轮询停止,会话切换到 websocket 连接.如果不成功,长轮询连接"保持打开并继续使用.

Long polling pretty much works everywhere, so that is used at first so you can get a "connection" right away. Then in the background, an attempt is made to upgrade the long polling connection to a websocket connection. If the upgrade is successful, the long polling stops and the session switches to the websocket connection. If it's not successful, the long polling "connection" stays open and continues to be used.

这篇关于为什么我的 socket.io 使用长轮询而不是 websocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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