最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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 ing from the WebSocket server?

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 ing from the WebSocket server?

Share Improve this question edited Apr 26, 2011 at 17:53 Chad Johnson asked Apr 26, 2011 at 17:46 Chad JohnsonChad Johnson 21.9k36 gold badges115 silver badges216 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

You can send data as a string. For example:

socket.send("hello world");

I remend 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 patible with UTF-8. For example, base64. This is covered in more detail in the answer linked above.

发布评论

评论列表(0)

  1. 暂无评论