WebSocket是一种在单个TCP连接上进行全双工通信的协议。它可以在客户端和服务器之间创建一个持久连接,使得服务器可以主动向客户端推送消息。
在PHP中,可以使用Ratchet库来实现WebSocket功能。
可以使用Composer安装Ratchet:
composer require cboden/ratchet
创建一个WebSocket服务器需要继承Ratchet的MessageComponentInterface接口,并实现onOpen、onMessage、onClose和onError方法。
php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// 当有新的客户端连接时执行
$this->clients->attach($conn);
}
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);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
// 发生错误时执行
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
在入口文件中实例化WebSocket服务器并启动:
php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
以上代码将在8080端口启动一个WebSocket服务器,并监听客户端的连接请求。
在客户端,可以使用JavaScript实现WebSocket的功能。
javascript
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log("Message received: " + e.data);
};
conn.onclose = function(e) {
console.log("Connection closed!");
};
conn.onerror = function(e) {
console.log("Error occurred: " + e.data);
};
以上代码创建了一个WebSocket连接,并监听服务器发送的消息。
可以使用conn.send()方法向服务器发送消息:
javascript
conn.send("Hello, server!");
以上代码向服务器发送了一条消息。