I found a post at https://stackoverflow.com/a/10402443/2755042 explaining how you can encode/frame and decode websocket data. I'm having troubles with the encoding part. I am able to successfully get data from the client and log it to the console, but when i turn around and re-encode that message and send it back to the client, I get an error:
net.js:614
throw new TypeError('invalid data');
^
TypeError: invalid data
Here is my code for encoding:
function encodeWebSocket(bytesRaw){
var bytesFormatted = new Array();
bytesFormatted[0] = 129;
if (bytesRaw.length <= 125) {
bytesFormatted[1] = bytesRaw.length;
} else if (bytesRaw.length >= 126 && bytesRaw.length <= 65535) {
bytesFormatted[1] = 126;
bytesFormatted[2] = ( bytesRaw.length >> 8 ) & 255;
bytesFormatted[3] = ( bytesRaw.length ) & 255;
} else {
bytesFormatted[1] = 127;
bytesFormatted[2] = ( bytesRaw.length >> 56 ) & 255;
bytesFormatted[3] = ( bytesRaw.length >> 48 ) & 255;
bytesFormatted[4] = ( bytesRaw.length >> 40 ) & 255;
bytesFormatted[5] = ( bytesRaw.length >> 32 ) & 255;
bytesFormatted[6] = ( bytesRaw.length >> 24 ) & 255;
bytesFormatted[7] = ( bytesRaw.length >> 16 ) & 255;
bytesFormatted[8] = ( bytesRaw.length >> 8 ) & 255;
bytesFormatted[9] = ( bytesRaw.length ) & 255;
}
for (var i = 0; i < bytesRaw.length; i++){
bytesFormatted.push(bytesRaw.charCodeAt(i));
}
return bytesFormatted;
}
Here is the code that uses the encodeWebSocket
function:
server.on('connection', function (socket) {
socket.on('data', function (data) {
// from client i send 'hello'
var decodedMessage = (decodeWebSocket(data));
console.log(decodedMessage); // hello
console.log(typeof decodedMessage); // string
var encodedMessage = encodeWebSocket(decodedMessage);
socket.write(encodedMessage);
});
});
Essentially, all I am trying to do is create a chat server that accepts a message, and turns around and sends it back to all other clients that are connected.
Any help is much appreciated.