网址:(记得挂梯子)
安装
composer require arthurkushman/php-wss
实现你的 WebSocket 处理程序类
例如:
<?php
use WSSC\Contracts\ConnectionContract;
use WSSC\Contracts\WebSocket;
use WSSC\Exceptions\WebSocketException;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class ServerHandler extends WebSocket
{
/*
* if You need to parse URI context like /messanger/chat/JKN324jn4213
* You can do so by placing URI parts into an array - $pathParams, when Socket will receive a connection
* this variable will be appropriately set to key => value pairs, ex.: ':context' => 'chat'
* Otherwise leave $pathParams as an empty array
*/
public $pathParams = [':entity', ':context', ':token'];
private $clients = [];
private $log;
/**
* ServerHandler constructor.
*
* @throws \Exception
*/
public function __construct()
{
// create a log channel
$this->log = new Logger('ServerSocket');
$this->log->pushHandler(new StreamHandler('./tests/tests.log'));
}
public function onOpen(ConnectionContract $conn)
{
$this->clients[$conn->getUniqueSocketId()] = $conn;
$this->log->debug('Connection opend, total clients: ' . count($this->clients));
}
public function onMessage(ConnectionContract $recv, $msg)
{
$this->log->debug('Received message: ' . $msg);
$recv->send($msg);
}
public function onClose(ConnectionContract $conn)
{
unset($this->clients[$conn->getUniqueSocketId()]);
$this->log->debug('close: ' . print_r($this->clients, 1));
$conn->close();
}
/**
* @param ConnectionContract $conn
* @param WebSocketException $ex
*/
public function onError(ConnectionContract $conn, WebSocketException $ex)
{
echo 'Error occured: ' . $ex->printStack();
}
/**
* You may want to implement these methods to bring ping/pong events
*
* @param ConnectionContract $conn
* @param string $msg
*/
public function onPing(ConnectionContract $conn, $msg)
{
// TODO: Implement onPing() method.
}
/**
* @param ConnectionContract $conn
* @param $msg
* @return mixed
*/
public function onPong(ConnectionContract $conn, $msg)
{
// TODO: Implement onPong() method.
}
}
要使用其唯一 ID 来保存客户端 - 使用getUniqueSocketId()
返回(类型转换为 int)socketConnection 资源 ID。
然后将下面的代码放入你的 CLI/控制台脚本并运行
<?php
use WSSC\WebSocketServer;
use WSSCTEST\ServerHandler;
use WSSC\Components\ServerConfig;
$config = new ServerConfig();
$config->setClientsPerFork(2500);
$config->setStreamSelectTimeout(2 * 3600);
$webSocketServer = new WebSocketServer(new ServerHandler(), $config);
$webSocketServer->run();
WebSocket 客户端连接
<?php
use WSSC\WebSocketClient;
use \WSSC\Components\ClientConfig;
$client = new WebSocketClient('ws://localhost:8000/notifications/messanger/yourtoken123', new ClientConfig());
$client->send('{"user_id" : 123}');
echo $client->receive();
就是这样,客户端只是向服务器发送任何文本内容(消息)。
服务器读取所有消息并将其推送到 Handler 类,以进行进一步的自定义处理。
最后强烈推荐!!