Skip to content

Instantly share code, notes, and snippets.

@andyg2
Created May 20, 2023 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyg2/6430d6b6e605c658b4261162dbcde20c to your computer and use it in GitHub Desktop.
Save andyg2/6430d6b6e605c658b4261162dbcde20c to your computer and use it in GitHub Desktop.
Simple PHP Websocket

Running

Start in shell WebSocket server: php -q websockets.php

Start in shell WebSocket client: php -S 0.0.0.0:8000 websockets.html please use separated tab in terminal.

Test

Open in browser URL: http://0.0.0.0:8000/ you will see current timestamp updating

<html>
<body>
<div id="root"></div>
<script>
var host = 'ws://0.0.0.0:12345/websockets.php';
var socket = new WebSocket(host);
socket.onmessage = function (e) {
document.getElementById('root').innerHTML = e.data;
};
</script>
</body>
</html>
<?php
$address = '0.0.0.0';
$port = 12345;
// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $address, $port);
socket_listen($server);
$client = socket_accept($server);
// Send WebSocket handshake headers.
$request = socket_read($client, 5000);
preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
$key = base64_encode(pack(
'H*',
sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
));
$headers = "HTTP/1.1 101 Switching Protocols\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Accept: $key\r\n\r\n";
socket_write($client, $headers, strlen($headers));
// Send messages into WebSocket in a loop.
while (true) {
sleep(1);
$content = 'Now: ' . time();
$response = chr(129) . chr(strlen($content)) . $content;
socket_write($client, $response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment