Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 746
Chad Johnson Avatar asked Feb 28 '26 04:02

Chad Johnson


2 Answers

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!

like image 131
Van Coding Avatar answered Mar 01 '26 16:03

Van Coding


You can send data as JSON objects.

 socket.send(JSON.stringify({field1:'0xEF', field2:'0x60',field3: '0x0042'}));
like image 40
kongaraju Avatar answered Mar 01 '26 16:03

kongaraju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!