The following article will provide, granularly, the steps of recording keyboard entry from a user of a Web.Sockets-chat and generating the payload frame that is ready to send to the server, through the protocol:
H3S1: Capturing user input, as an ASCII string:
Hu: Again, we will always be working with single stroke kb-input. For the MVP, we can simply use an HTML form, to capture the single.char-string.
H3S2: Building an internal library for char to binary encoding:
H3S3: Measuring the length, in binary integers, of the resulting encoded:
Hu: The length will be recorded as an ASCII integer, in this step.
H3S4: Encoding the integer length, also, into binary:
H4S1: decbin:
<php.net>: Returns a string containing a binary | representation of the given num
argument.
decbin(int $num): string
//example:
echo decbin(12) . " | ";
echo decbin(26);
Output: 1100 | 11010
H4S2: pack:
pack(string $format, mixed ...$values): string
<php.net>: Pack given arguments into a binary string according to format
<see-doc>: Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
<php.net>: The resulting binary string will be 6 bytes long and contain the byte sequence <hexadecimal:>0x12, 0x34, 0x78, 0x56, 0x41, 0x42.
H4S3: base_convert:
<php.net>: Returns a string containing num
represented in base to_base
. The base in which num
is given is specified in from_base
. Both from_base
and to_base
have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35. The case of the letters doesn’t matter, i.e. num
is interpreted case-insensitively.
base_convert(string $num, int $from_base, int $to_base):
string
//example:
$hexadecimal = 'a37334';
echo base_convert($hexadecimal, 16, 2);
Output: 101000110111001100110100
H3S5: Translating the integer string # into binary:
Hu: This binary representation needs to be exactly 7 bits, regardless of the integer length, which is between 0 and 125, inclusive #
H3S6: Appending the integer.representation-binary at the end of the 2.byte-header:
Hu: The FIN value of an unchained messages is //
H3S7: Appending the user.input-encoded,binary to the end of the 2.byte-header:
Hu: This should be the last step. The value returned by this function is ready to be sent # into the server via the Web.Socket-protocol. On the other side, the decode should reverse these steps, in the same | order<Turing>
References:
https://websockets.readthedocs.io/en/3.3/api.html#module-websockets.framing
https://www.rfc-editor.org/rfc/rfc6455
https://www.openmymind.net/WebSocket-Framing-Masking-Fragmentation-and-More/