我如何在 Javascript 中通过 WebSocket 发送和接收数据包
我想将数据从 Javascript 发送到 WebSocket 服务器,也从 WebSocket 服务器发送到 Javascript。
我想发送这个:
Headers
-------
Field 1: 2 byte hex
Field 2: 2 byte hex
Field 3: 4 byte hex
Data
----
Field1 : 2 byte hex
Field1 : 8 byte hex
从 Javascript,我可以通过以下方式发送一个两字节值
socket = new WebSocket(host);
...
socket.send(0xEF);
但我想发送多个字段,一起...比方说 0xEF、0x60 和 0x0042。
我该怎么做?
并且,如何通过 Javascript 解释来自 WebSocket 服务器的包含多个字段的数据?
I want to send data from Javascript to a WebSocket server and also from a WebSocket server to Javascript.
I want to send this:
Headers
-------
Field 1: 2 byte hex
Field 2: 2 byte hex
Field 3: 4 byte hex
Data
----
Field1 : 2 byte hex
Field1 : 8 byte hex
From Javascript, I can send a two-byte value via
socket = new WebSocket(host);
...
socket.send(0xEF);
But I want to send multiple fields, together...let's say 0xEF, 0x60, and 0x0042.
How do I do this?
And, how to I interpret via Javascript data containing multiple fields coming from the WebSocket server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将数据作为字符串发送。例如:
我建议您使用 JSON 作为数据格式。您可以将 JSON 字符串直接转换为对象,反之亦然。它是如此简单和有用!
You can send data as a string. For example:
I recommend you to use JSON as data format. You can convert JSON strings directly into objects and vice versa. It's so simple and useful!
您可以将数据作为 JSON 对象发送。
You can send data as JSON objects.
听起来您要问的是如何通过 WebSocket 连接发送二进制数据。
这很大程度上在这里得到了回答:
使用 Javascript 通过 Web 套接字发送和接收二进制数据 当前
该答案中未涵盖一些额外信息:
的 WebSocket 协议和 API 只允许发送和接收字符串(或任何可以强制/类型转换为字符串的内容)消息是字符串。支持二进制数据的协议的下一个迭代 (HyBi-07) 目前正在浏览器中实现。
Javascript 字符串是 UTF-16,内部每个字符占 2 个字节。当前的 WebSockets 有效负载仅限于 UTF-8。在 UTF-8 中,低于 128 的字符值需要 1 个字节进行编码。值 128 及以上需要 2 个或更多字节进行编码。当您发送 Javascript 字符串时,它会从 UTF-16 转换为 UTF-8。要发送和接收二进制数据(直到协议和 API 本身支持它),您需要将数据编码为与 UTF-8 兼容的内容。例如,base64。上面链接的答案对此进行了更详细的介绍。
Sound like what you are asking is how to send binary data over a WebSocket connection.
This is largely answered here:
Send and receive binary data over web sockets in Javascript?
A bit of extra info not covered in that answer:
The current WebSocket protocol and API only permits strings to be sent (or anything that can be coerced/type-cast to a string) and received messages are strings. The next iteration of the protocol (HyBi-07) supports binary data is currently being implemented in browsers.
Javascript strings are UTF-16 which is 2 bytes for every character internally. The current WebSockets payload is limited to UTF-8. In UTF-8 character values below 128 take 1 byte to encode. Values 128 and above take 2 or more bytes to encode. When you send a Javascript string, it gets converted from UTF-16 to UTF-8. To send and receive binary data (until the protocol and API natively support it), you need to encode your data into something compatible with UTF-8. For example, base64. This is covered in more detail in the answer linked above.