I have this example array:
[{
id: 1,
name: "test",
position: [1234,850], // random position on the map
points: 100 // example points
}];
Here is what I want to do:
- Convert the array into binary data, and send the binary to my WebSocket server.
- On the server, decode the binary into an array and make changes.
- Convert the array into binary, and send the binary to the client.
- On the client, decode the binary back into an array.
Example screenshot of what I mean:
This is my actual code:
var connection = new WebSocket('wss://my_website.eu:1234');
connection.binaryType = "ArrayBuffer";
connection.onmessage = function (event) {
// console.log(event);
if (event.data instanceof window["ArrayBuffer"]) {
var data3 = JSON.parse(String.fromCharCode.apply(null, new Uint16Array(event.data)));
console.log(data3);
} else {
console.log(event.data); // Blob {size: 0, type: ""}
}
};
$("body").mousemove(function( event ) {
var data = {
name: "lol",
pos: [event.pageX, event.pageY]
};
// convert to binary frame
var data2 = new Uint16Array(data);
console.log(data2); // []
// try to convert back to array
var data3 = String.fromCharCode.apply(null, new Uint16Array(data2));
console.log(data3); // empty
connection.send(data2); // Binary Frame (Opcode 2, mask) | length: 0
});
Server-side code:
connection.on('message', function(message) {
for (var i = players.length - 1; i >= 0; i--) {
players[i].connection.send(message.binaryData);
}
});
LATEST EDIT READ FROM HERE
I now can send a message as a binary frame to a WebSocket server. I found functions to convert a string to a binary type and send it to a WS server.
Now I have a problem. This function (below) is not working at server-side. Example code:
var data = {
name: "value"
};
connection.send(JSON.stringify(data));
This code is working good. Now, when I try to send as an array buffer:
var data = {
name: "value"
};
connection.send(StringToArrayBuffer(JSON.stringify(data)));
the output is not a binary frame. It is just a string [object ArrayBuffer]
:
I also tried:
connection.send(JSON.stringify(data), {binary: true, mask: false});
but this is sending the message as a normal string, not a binary frame.
So, how I can send a binary frame from a WebSocket server to a client? When I send back a received binary message:
connection.on('message', function(message) {
for (var i = players.length - 1; i >= 0; i--) {
playerConnection[i].send(message.binaryData);
}
}
only this works.