Skip to content

Instantly share code, notes, and snippets.

@lrdgz
Created July 26, 2018 16:23
Show Gist options
  • Save lrdgz/5fb5a1b9cf133cd17f1bc025bc05d6dc to your computer and use it in GitHub Desktop.
Save lrdgz/5fb5a1b9cf133cd17f1bc025bc05d6dc to your computer and use it in GitHub Desktop.

Engagement Start in shell WebSocket server: php -q websockets.php. Start in shell WebSocket client: php -S 127.0.00.1: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 which will continuously updating! Hence, it works!

Conclusion This is just super simple PHP WebSocket example. Yes, it isn’t real world example, but it is as simple as possible sample which you can use as starting basis for your next experiments!

<html>
<body>
<div id="root"></div>
<script>
var host = 'ws://127.0.0.1:12345/websockets.php';
var socket = new WebSocket(host);
socket.onmessage = function(e) {
document.getElementById('root').innerHTML = e.data;
};
</script>
</body>
</html>
<?php
$address = '127.0.0.1';
$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