I started learning web sockets ... I wrote a server in PHP that handles messages of a certain format. The server works fine with a client in C ++, which simply connects to the required localhost port and starts data exchange. But with the browser trouble ... The server writes that Client connected ... But the browser does not just connect, but immediately sends HTTP headers with Connection Upgrade, etc. Naturally, the server does not handle these headers in any way, as it waits for a message of a different format, and in the browser console I see the sent headers and the endless receiving of the answer. Naturally expected alert("Connection established"); does not appear

Should I manually handle these headers? Maybe something wrong doing? How to automate this browser formality upgrade on WS?

  • Do not write the answer in the question. Better add your answer and tick it off. So others will be able to vote for him and the question will not hang like "without answers." - Arnial

1 answer 1

All figured out!

 define('WS_GIUD', '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); define('WS_KEY_MARKER', 'Sec-WebSocket-Key: '); ... switch ($Data[0]){ case 'G': // GET / HTTP ... $KeyStart = strpos($Data, WS_KEY_MARKER); // 'Sec-WebSocket-Key: ' if ($KeyStart){ $KeyStart += strlen(WS_KEY_MARKER); $SecureKey = substr($Data, $KeyStart, strpos($Data, 0x0D0A, $KeyStart) - $KeyStart - 1); $Handshake = "HTTP/1.1 101 Switching Protocols\r\n" ."Upgrade: websocket\r\n" ."Connection: Upgrade\r\n" ."Sec-WebSocket-Accept: ".base64_encode(sha1($SecureKey.WS_GIUD, true))."\r\n\r\n"; socket_write($Socket, $Handshake); } else{ socket_close($Socket); unset($Clients[$Socket_key]); break; } break;