How to implement long connection communication in PHP?
In traditional Web applications, short connections are usually used for communication. Whenever a client sends a request to the server, the server processes the request and returns a response, then immediately disconnects. In some specific application scenarios, such as real-time chat, push messages, etc., long connections need to be implemented for real-time data interaction. This article will introduce how to implement long connection communication in PHP, with code examples.
To implement long connections in PHP, you can use the following two common technologies: polling and WebSocket.
The following is a simple polling example code:
<?php // 服务器端 $data = "Hello, World!"; // 待推送的数据 while (true) { $newData = checkNewData(); // 检查是否有新数据 if ($newData) { echo $newData; flush(); // 立即发送响应 break; } usleep(1000); // 休眠1毫秒,避免CPU占用过高 } // 客户端 set_time_limit(0); // 取消超时时间限制 while (true) { $response = sendRequest(); // 发送请求 if ($response) { echo $response; } usleep(1000); // 休眠1毫秒 }
The following is a simple WebSocket sample code:
<?php // 服务器端 $server = new WebSocketServer("localhost", 8000); // 创建WebSocket服务器对象 while (true) { $client = $server->accept(); // 接受客户端连接 while (true) { $message = $client->receive(); // 接收客户端消息 if ($message) { // 处理客户端消息 // $data = processMessage($message); // 将处理后的数据推送给客户端 // $client->send($data); } } $client->close(); // 关闭客户端连接 } // 客户端 $socket = new WebSocketClient("ws://localhost:8000"); // 创建WebSocket客户端对象 while (true) { $message = $socket->receive(); // 接收服务器消息 if ($message) { // 处理服务器消息 // $data = processMessage($message); // 将处理后的数据展示给用户 // echo $data; } // 发送消息给服务器 // $socket->send($message); }
The above is a brief introduction and sample code on how to implement long connection communication in PHP. To achieve more complex long-connection communication, more technologies and tools may be needed. I hope this article can help you understand and use long connection communication.
The above is the detailed content of How to implement long connection communication in PHP?. For more information, please follow other related articles on the PHP Chinese website!