2

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?

3 Answers 3

8

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!

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the idea to use JSON, but I'm not sure I'm going to do that.
4

You can send data as JSON objects.

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

Comments

3

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.

2 Comments

Regarding "Javascript strings are UTF-16 which is 2 bytes for every character internally", do you have a source? Doesn't it depend on the encoding of the file itself?
@Pacerier: the encoding of strings internally by the browser/javascript engine is not dependent on the Javascript source code encoding. Internally strings are UTF-16. More info than you ever wanted here: mathiasbynens.be/notes/javascript-encoding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.