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?

Chad Johnson
  • 21,215
  • 34
  • 109
  • 207

3 Answers3

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!

Van Coding
  • 24,244
  • 24
  • 88
  • 132
4

You can send data as JSON objects.

 socket.send(JSON.stringify({field1:'0xEF', field2:'0x60',field3: '0x0042'}));
kongaraju
  • 9,344
  • 11
  • 55
  • 78
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.

Community
  • 1
  • 1
kanaka
  • 70,845
  • 23
  • 144
  • 140
  • 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 Jul 17 '12 at 19:21
  • 1
    @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: http://mathiasbynens.be/notes/javascript-encoding – kanaka Jul 17 '12 at 19:39