Skip to content Skip to sidebar Skip to footer

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 h

Solution 1:

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!

Solution 2:

You can send data as JSON objects.

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

Solution 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.

Post a Comment for "How Would I Send And Receive Packets Over A Websocket In Javascript"