Transmitting information through websockets in binary form involves converting numbers into text for encoding

I have a project in which I need to transmit binary data over a websocket connection to an LED matrix. My plan is to send the binary data as a byte array, for example, creating a diagonal line from right to left on the matrix would be represented like this:

0b00000001
0b00000010
0b00000100
0b00001000
0b00010000
0b00100000
0b01000000
0b10000000

However, when attempting to send this data, regardless of the WebSocket client tool I use, the numbers are being encoded as strings.

For instance, when attempting to send the binary number 1, instead of transmitting 0x01, the socket client is sending 49 in decimal/0x31 in hex, which represents the character code for the string '1' in ASCII or Unicode.

This encoding issue seems to occur at the client side during websocket transmission, rather than being related to the Arduino code controlling the matrix or the server itself, as confirmed by monitoring with Wireshark.

The same problem persists whether using Firecamp or another client such as websocat:

Given these challenges, my question is: what is the correct method for sending binary numbers via websockets? Could it be that I am misunderstanding how the binary feature operates, and should I be sending numbers as strings and converting them back at the receiving end?

Answer №1

After conducting research and introspection, I successfully identified the root of my problem. @myst also mentioned it in the preceding comment.

In the scenario where I inputted a number into the websocat command's interactive prompt without quotation marks, assuming it would be recognized as an integer, it actually treated the input as a string (which, in hindsight, makes sense for command-line tools handling arguments).

Similarly, when I attempted to add numbers by creating a test file, I mistakenly expected them to be recognized as numeric values but they were interpreted as strings.

During troubleshooting, I realized that sending binary data - like an image file - results in actual binary content being transmitted, rather than text representation.

For instance, running cat myimage.png won't display binary numbers; instead, it appears as garbled characters and spaces.

https://i.sstatic.net/ZZk8M.jpg

This "garble" isn't random; it signifies outputting sequences of binary code, with some elements lacking character encoding equivalents (resulting in blanks) while others align with character encodings but appear disorderly, resembling gibberish.

To grasp the concept better, I referred to a helpful guide on manually creating a binary file posted on Super User:

The technique involves utilizing the printf command.

$ printf "\x08\x00\x00\x10" > file1
$ hexdump file1
00000000  08 00 00 10                                   |....|
00000004

With this newfound knowledge, I crafted a binary file containing a simple hexadecimal progression from 1 to 8, which I then piped into the websocat utility:

printf "\x01\x02\x03\x04\x05\x06\x07\x08" > binfile \
> cat binfile | websocat -b ws://localhost:3002

This action yielded the intended result:

https://i.sstatic.net/wAkHP.jpg

Furthermore, upon revisiting the process without involving a file write operation, executing the command directly worked flawlessly:

printf "\x01\x02\x03\x04\x05\x06\x07\x08" | websocat -b ws://localhost:3002

Although the method didn't function as anticipated in Firecamp initially, discussions are ongoing with their engineers, including testing on a canary version for potential resolution.

I have now resolved the issue and am prepared to revisit and revise some of the existing code :P

Additional Insights

Collaborating with the Firecamp developers revealed that their message types for Array Buffer and Array Buffer View inadvertently conveyed ASCII codes instead of raw numerical values. Subsequent adjustments have rectified this matter (confirmed via a canary release), scheduled for inclusion in v2.0.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The authentication middleware is being executed for all routes within my app.js file, despite my intention to only apply it to a single route

I have developed a requireAuth middleware and integrated it into my app.js. In app.js, I have also imported all the routes from the routes folder. Each route.js file contains multiple chained routes. When I include the auth middleware in one of those files ...

Creating an Engaging Data Visualization: Blending Candlestick Insights with Line Graphs

I'm attempting to display a moving average on a candlestick chart, but I'm facing an issue where the path of the line is not fully appearing on the SVG canvas that I've created. I've searched through various posts to understand how to o ...

I am looking to retrieve a sophisticated/nested JSON data using jQuery

I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...

Inserting an item into a list

Looking for assistance with this particular scenario: { "EekvB3cnwEzE":{ "name":"hi", }, "Brv1R4C6bZnD":{ "name":"yup", }, "kRwRXju6ALJZ":{ "name":"okay", } } I'm attempting to store each of these objects in an array. Howe ...

The Ajax Control Upload consistently defaults to the default value and disregards any text input selected from the drop-down list

On my website, I have implemented an ajax control upload event that allows users to upload a zip file and then unzip it using zlib. The folder name for unzipping is created based on the selection from a dropdown list. However, I am facing some issues where ...

Can JQuery be used to detect text input in real-time in a textarea field?

Currently, I have a button for "post" that becomes active when text is typed into the text area. The issue arises when all text is deleted from the text area, as the button remains active in its coloured state despite being disabled using the following cod ...

When using TypeScript with custom components as children in React, the `type` returned by React.Children is a string representing the function

It might sound a bit odd, or maybe I'm completely off track here. While going through some articles and React documentation on getting children and identifying specific child components using React.Component.map(), I ran into an issue with my custom c ...

What is a global variable used for in JavaScript?

Here is the code snippet that I am currently working on: $(".link").each(function() { group += 1; text += 1; var links = []; links[group] = []; links[group][text] = $(this).val(); } ...

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...

Incorporating ZeroClipboard or ZClip (button for copying to clipboard) using JQuery's Ajax functionality

Seeking to implement a 'copy to clipboard' feature triggered by clicking. However, I am facing a challenge as this functionality needs to be integrated with other content loaded using Ajax. Many plugins that achieve the same use Flash to bypass ...

Angular Typescript error: Trying to assign a value to 'someProperty' property of an undefined object

Within my Article class, I have a property called Image which is structured like this: export class Article { public image:Image; public images: Image[]; } If I decide to comment out this.article.image = new Image(); in the following way: constru ...

Using Javascript to dynamically add and remove elements on click

Whenever I click on a link, I am able to generate input, label, and text. However, I want to be able to delete these elements with the next click event on the same link: I've tried updating my code like this: var addAnswer = (function() { var la ...

Calculating date discrepancies with JavaScript

Two fields are present, one for the start date and one for the end date. I would like to display the date difference in another text box when the user selects dates from a date picker. Although I have made some progress on this, I believe that there are st ...

Obtaining the initial row information from jqGrid

If I use the getRowData method, I can retrieve the current cell content instead of the original data before it was formatted. Is there a way to access the original content before any formatting transformations are applied? Just so you know, I am filling t ...

Sorting arrays in javascript

My JavaScript array is structured like this: var data_tab = [[1,id_1001],[4,id_1004],[3,id_1003],[2,id_1002],[5,id_1005]] I am looking to organize and sort them based on the first value in each pair: 1,id_1001 2,id_1002 3,id_1003 4,id_1004 5,id_1005 ...

The Lerna command for adding packages fails with an error message stating that the packages are not related

Currently, I am utilizing lerna to manage a multirepo containing interrelated packages. This issue only arose after installing a new operating system. Whenever I attempt to utilize lerna add to add a dependency from one package to another, an error occurs ...

Is there a way to determine if the browser window is currently in use?

The code I am currently working with looks like this: let focus; function setFocus() { focus = true; } function hideWindow() { focus = false; } window.onfocus = setFocus(); window.onblur = hideWindow(); The intention behind this code is to use it in the ...

Adding options to a select element using JavaScript dynamically

Is there a way to create a dynamic select list for year values using JavaScript? <form action="something"> some other fields <select id="year"> </select> </form> ...

Ways to show an input box even when there are no results found

I currently have a database with 5 books, but only 3 of them have prices listed. How can I modify my code to display an input box for all books, regardless of whether they have a price in the database? I am new to coding, so I would appreciate it if you co ...

A guide to storing a JavaScript variable in a MySQL database using Express.js

Looking for some guidance on node js and expressjs framework. While developing a web application, I've encountered an issue with saving data into the database. Everything seems to be set up correctly, but the data stored in the variable (MyID) is not ...