How to Create a WebSocket Server in PHP
Introduction
WebSockets enable real-time communication between a web client and a server. To utilize this technology in PHP, you can follow the steps outlined below.
1. Understanding WebSocket
2. Implementing the Handshake
3. Message Handling
4. Connection Handling
Troubleshooting
Example Script
Here's a simplified example PHP script for a WebSocket server:
<?php // Initialize server $master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($master, 'localhost', 12345); socket_listen($master, 20); // Accept incoming connections $sockets = array($master); while (true) { $changed = $sockets; socket_select($changed, $write, $except, null); foreach ($changed as $socket) { if ($socket == $master) { // Accept new connection $client = socket_accept($master); $sockets[] = $client; } else { // Receive data from client $data = socket_read($socket, 2048); // Process data and respond appropriately socket_write($socket, wrap($data)); } } } ?>
Client-Side Script
var connection = new WebSocket('ws://localhost:12345'); connection.onmessage = function (e) { console.log(e.data); };
Additional Tips
The above is the detailed content of How to Build a Real-time WebSocket Server with PHP?. For more information, please follow other related articles on the PHP Chinese website!