I want send this example array
[{
id: 1,
name: "test",
position: [1234,850], //random position on the map
points: 100 //example points
}];
to my websocket server as binary data. At server side I want decode that binary data back into array, make changes and send back binary data to client. And finally at client side how to decode binary data back into array?
Example screenshot 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 message as binary frame to websocket server. I found functions to convert string to binary type and send it to ws server.
Now I have problem. This functions (below) not working at server-side. Example code:
var data = {
name: "value"
};
connection.send(JSON.stringify(data));
This code working good. Now, when I try to send as array buffer:
var data = {
name: "value"
};
connection.send(StringToArrayBuffer(JSON.stringify(data)));
output is not Binary frame, is just string "[object ArrayBuffer]":
I also tried:
connection.send(JSON.stringify(data), {binary: true, mask: false});
but this sending message as normal string, not binary frame.
So, how I can send Binary frame from websocket server to client? When I send back 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.