Use PHP to develop Websocket to implement instant chat function
Websocket is a full-duplex communication protocol, suitable for real-time communication scenarios, such as instant chat and real-time data updates wait. As a popular server-side programming language, PHP can also implement Websocket functions through related libraries and extensions. In this article, we will introduce how to use PHP to develop Websocket. The specific code examples are as follows.
First of all, you need to ensure that the server supports the Websocket protocol. In PHP, you can use the Ratchet library to implement a Websocket server. Ratchet is a library based on ReactPHP that provides a simple and flexible operation interface.
Use Composer to install the Ratchet library. You can execute the following command in the project directory:
composer require cboden/ratchet
Create a file named server.php in the root directory of the project and write the following code:
<?php require __DIR__.'/vendor/autoload.php'; use RatchetMessageComponentInterface; use RatchetConnectionInterface; use RatchetServerIoServer; use RatchetHttpHttpServer; use RatchetWebSocketWsServer; class Chat implements MessageComponentInterface { protected $clients; public function __construct() { $this->clients = new SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); echo "New connection! ({$conn->resourceId}) "; } public function onMessage(ConnectionInterface $from, $msg) { foreach ($this->clients as $client) { if ($client !== $from) { $client->send($msg); } } } public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); echo "Connection {$conn->resourceId} has disconnected "; } public function onError(ConnectionInterface $conn, Exception $e) { echo "An error occurred: {$e->getMessage()} "; $conn->close(); } } $server = IoServer::factory( new HttpServer( new WsServer( new Chat() ) ), 8080 ); echo "Server running at http://localhost:8080 "; $server->run();
Enter the project root directory on the command line and execute the following command to start the Websocket server:
php -f server.php
At this point, the Websocket server has been started and is listening on port 8080. It can be accessed through http://localhost:8080.
Create a file named index.html in the project directory and write the following code:
<!DOCTYPE html> <html> <head> <title>Websocket Chat</title> <script> var socket = new WebSocket("ws://localhost:8080"); socket.onopen = function(event) { console.log("Socket opened"); }; socket.onmessage = function(event) { console.log("Message received: " + event.data); }; socket.onclose = function(event) { console.log("Socket closed"); }; function sendMessage() { var message = document.getElementById("message").value; socket.send(message); } </script> </head> <body> <input type="text" id="message" placeholder="Type a message"> <button onclick="sendMessage()">Send</button> </body> </html>
In the browser Open the index.html file in and you will see an input box and button for sending messages. Enter a message in the input box and click the Send button to send the message to the server.
Open multiple browser windows or tabs, enter different messages respectively, and click the send button. You will find that the message will be broadcast to all connected clients.
So far, we have successfully developed a simple Websocket server using PHP to implement the instant chat function. Through the encapsulation of the Ratchet library, we can quickly implement complex Websocket applications. I hope this article is helpful to you, and I wish you happy programming!
The above is the detailed content of Use php to develop Websocket to implement instant chat function. For more information, please follow other related articles on the PHP Chinese website!