握手后立即发送 WebSocket 消息

发布于 2024-11-18 12:18:45 字数 479 浏览 4 评论 0原文

我正在 node.js 中构建一个 WebSocket 服务器。当客户端连接后,我想立即向其发送一条消息。

但是,当我在握手完成后立即发送消息时,我在 Chrome 中收到错误:

Status line contains embedded null

当我使用 setTimeout 在握手后 100 毫秒发送消息时,它可以工作,但之后又会这样使用此技术时,如果使用 10 毫秒,则不起作用。

看起来握手和消息在一起发送时会被附加,以防它们之间的时间间隔很短(尽管我不确定,因为我不知道如何在 Chrome 中查看原始 WebSocket 流量- 如果有人这样做,我也很想听听)。

我不想让服务器等待 100 毫秒,因为这对于客户端来说肯定是显而易见的,而且它看起来像是一个肮脏的把戏,而不是一个好的解决方案。

握手后如何立即发送消息?

I'm building a WebSocket server in node.js. When a client has connected, I'd like to send a message immediately to it.

However, when I send it just after the handshake has completed, I get an error in Chrome:

Status line contains embedded null

When I use a setTimeout to send the message 100 milliseconds after the handshake, it works, but then again it does not work when using 10 milliseconds using this technique.

It looks like the handshake and the message get appended when sent together in case the time interval between them is small (though I'm not sure since I don't know how to view raw WebSocket traffic in Chrome - if someone does I'd love to hear that as well).

I do not want to have the server wait 100 milliseconds because it is certainly noticeable for the client, and moreover it looks like a dirty trick rather than a nice solution.

How can I send a message immediately after a handshake?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦回梦里 2024-11-25 12:18:45

我已经整理好了 - 我是在有连接时发送的,但这当然是在发送握手之前。所以我正在做:

client connected
send message
receive handshake request
send handshake response
...

我只是通过在发送握手时触发我的库的 connect 事件来更改我的代码,这是在 WebSocket 连接真正建立时。

作为旁注,我想提一下 chrome://net-internals/ 在调试 WebSocket 连接时是一个非常有用的页面(您可以轻松地看到请求/响应握手)。我早该知道的...

I sorted it out already - I was sending it when there was a connection, but this is before the handshake is sent of course. So I was doing:

client connected
send message
receive handshake request
send handshake response
...

I just altered my code by firing the connect event of my library when the handshake is sent, which is when the WebSocket connection is really established.

As a side note, I would like to mention that chrome://net-internals/ is a very helpful page when debugging WebSocket connections (you can easily see the request/response handshake). I should have known that earlier...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文