开发者

How would I send and receive packets over a WebSocket in Javascript

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.开发者_StackOverflow..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?


You can send data as a string. For example:

socket.send("hello world");

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!


You can send data as JSON objects.

 socket.send(JSON.stringify({field1:'0xEF', field2:'0x60',field3: '0x0042'}));


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜