Pregunta

how can I tell an html5 message payload length over websockets?

Im aware the base protocol consists of an op code, then length is determine by the next 1 to 8 bytes, then the following values is the hashing and then the rest is payload!

Im creating a java serverside application that will receivea message from a html5 client and then handle, iI can handle messages up to 256 bytes.

Any help to work this out even manually would be great (i.e how to habdle the bytes that determine the payload)

Cheers

¿Fue útil?

Solución

There are three ways how the payload length of a websocket frame can be encoded, which depend on the length of the payload:

  1. 125 or less
  2. 126-65535
  3. 65536 +

Which way is used can be told by looking at the value of the 7 last bits of the 2nd byte (the first bit of the 2nd byte is the masking flag).

When it's below 126, it's the payload length. When it's 126, the payload length is in the following two bytes. When it's 127, the payload length is in the following 8 bytes.

So the algorithm you have to follow to interpret a websocket frame is:

  1. read the 1st byte ("byte0") to get the fin flag and the opcode
  2. read the 2nd byte ("byte1")
  3. when byte1 is greater than 127, subtract 127 from byte1 and set masked to true
  4. when byte1 is now 126, read the next two bytes and convert it to a short. This is the payload_length.
  5. when byte1 is 127, read the next eight bytes and convert it to a long. This is the payload_length.
  6. when byte1 is something else, the payload_length is equal to the value of byte1
  7. when masked is true, read the next 4 byte. This is the masking_key.
  8. read the number of bytes you have in the payload_length to get the payload.
  9. when masked is true, apply the masking_key to the payload.

There is no hash-code in a websocket frame, you must have mixed something up. The integrity of a websocket frame is ensured by the TCP layer beneath it.

For more information about the Websocket protocol, refer to the RFC 6455.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top