3

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

Ghasem
  • 14,455
  • 21
  • 138
  • 171
BenJacob
  • 957
  • 10
  • 31
  • 1
    How long are the message you are trying to send? If it's larger than 125 bytes you need to encode the length in a different manner i.e you must take the extended payload length into consideration. – Cyclonecode Jul 07 '15 at 10:22
  • Right, of course, so i need to use the next two (or eight) bytes to store the length instead? – BenJacob Jul 07 '15 at 10:25
  • If the length is between 15 and 65535 bytes then your will have to add a two byte extended length, while if it's larger than 65535 bytes than you'll need a 4 byte extended length. – Cyclonecode Jul 07 '15 at 10:25
  • 1
    Checkout http://tools.ietf.org/html/rfc6455, you also have an example here on how to encode your header based on the payload size (this is an php example) https://github.com/CycloneCode/WSServer/blob/master/src/WSServer.php – Cyclonecode Jul 07 '15 at 10:26
  • Here is another example: http://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages-on-the-server-side – Cyclonecode Jul 07 '15 at 10:29
  • Awesome, thanks that helps a lot. (i think you meant 125 not 15 in your second comment) – BenJacob Jul 07 '15 at 10:32
  • Haha, yes i did, sorry still a little bit tired =) – Cyclonecode Jul 07 '15 at 10:32

1 Answers1

0

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);
Manushin Igor
  • 3,398
  • 1
  • 26
  • 40