'Websocket invalid frame header

I am sending data from a java server to a javascript client via a websocket in the following manner:

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 am unsure whether this is an issue with the op-code or something else.

Many thanks, Ben



Solution 1:[1]

Issue is here:

byteStream.write(bytes.length);

There are different schemas, how to encode integer into the byte array. Please see Endianness wikipedia article.

You have to do something by this (this code fragment is from .Net WebSocket client):

var arrayLengthBytes = BitConverter.GetBytes(bytes.length)

if (!BitConverter.IsLittleEndian)
{
    Array.Reverse(arrayLengthBytes, 0, arrayLengthBytes.Length);
}

byteStream.write(arrayLengthBytes);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manushin Igor