Invalid Websocket frame header
I am sending data from java server to client javascript
using websocket
like this:
private byte[] makeFrame(String message) throws IOException {
byte[] bytes = message.getBytes(Charset.forName("UTF-8"));
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byteStream.write(0x81);
byteStream.write(bytes.length);
byteStream.write(bytes);
byteStream.flush();
byteStream.close();
byte[] data = byteStream.toByteArray();
}
But I am getting the error
Websocket connection to 'ws://localhost:8080/' failed: Invalid frame header
when the size is large (I believe above 128 bytes). I'm not sure if this is a problem with the op code or something.
Thanks a lot Ben
+3
source to share
1 answer
The problem is here:
byteStream.write(bytes.length);
There are different schemes for how to encode an integer into a byte array. Please see the Endianness article on Wikipedia.
You have to do something with this (this piece of code from the .Net WebSocket client ):
var arrayLengthBytes = BitConverter.GetBytes(bytes.length)
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(arrayLengthBytes, 0, arrayLengthBytes.Length);
}
byteStream.write(arrayLengthBytes);
0
source to share