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

7
  • 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. Commented Jul 7, 2015 at 10:22
  • Right, of course, so i need to use the next two (or eight) bytes to store the length instead? Commented Jul 7, 2015 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. Commented Jul 7, 2015 at 10:25
  • 1
    Checkout 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) github.com/CycloneCode/WSServer/blob/master/src/WSServer.php Commented Jul 7, 2015 at 10:26
  • Here is another example: stackoverflow.com/questions/8125507/… Commented Jul 7, 2015 at 10:29

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.