I'm trying to code my own PHP server for WebSockets. The server sees the connections and receives opening handshakes of the latest version (8). Everything works fine so far, handshakes are working and the client has a solid connection.
Receiving messages works fine as well, but when I want to reply to clients, my code does not seem to work.
I have the following serverside code to send messages to clients:
public function write($data, $handshake = false) {
if ($handshake) {
socket_write($this->socket, $data.chr(0), strlen($data)+1);
} else {
socket_write($this->socket, chr(0).$data.chr(255), strlen($data)+2);
}
}
//Where $data is a JSON string
I believe part is clear; the first socket_write is used at the handshake, the other on for every normal messages (e.g. all messages except the handshake).
When I send my first message to a client, the client disconnects (only this client). I've replaced the chr(0) and chr(255) to almost every place (both before $data, both behind, only one in front/behind, etc.), but none seem to make any difference.
When I change these, the client doesn't disconnect, but doesn't receive a message either.
I was hoping you could send me in the right direction as there is almost no content on the latest WebSocket draft which I use: hybi-17.
Thanks!
Edit: Below is the message format I have to use (see Len Holgate's reply):
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
I have however, no idea how to build it as I have no experience with such a diagram. A small example or basic explanation would come in very handy.