后端主动发送消息到 Websocket 服务中的几种方式
常见的应用场景:跨服发消息,http服务推送到ws服务
1、php 原生方法
需要开启 sockets 扩展,自行问 AI 即可。
$client = stream_socket_client($host);
if (!$client) return false;
$sendData = [...];
fwrite($client, json_encode($sendData));
fclose($client);
2、swoole模拟客户端
$client = new Swoole\Client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1)) {
exit("connect failed. Error: {$client->errCode}\n");
}
$client->send("hello world\n");
echo $client->recv();
$client->close();
3、workerman模拟客户端
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker();
$worker->onWorkerStart = function($worker){
$con = new AsyncTcpConnection('ws://echo.websocket.org:80');
// websocket握手成功后
$con->onWebSocketConnect = function(AsyncTcpConnection $con, ) {
$con->send('hello');
};
// 当收到消息时
$con->onMessage = function(AsyncTcpConnection $con, $data) {
echo $data;
};
$con->connect();
};
Worker::runAll();
4、redis 队列
将数据写入队列中,然后在ws服务中启动一个定时器,依次出队,发送。
5、swoole多端口监听
添加一个 udp 的监听服务,使用 sendto 发送消息到 udp 服务的packet接收回调中,然后再使用 ws的server->push 发送。
本作品采用《CC 协议》,转载必须注明作者和本文链接
workman需要处理 应用层的ws握手设置回调。swoole直接原生tcp就行了?
workerman
没用过,swoole
有onRequest
接受Http
请求。22
websocket开始用laravel-echo-server,使用中发现文档少,遇到问题也无人过多讨论,除了直接用pusher驱动没有怎么遇到问题外,用其他的总是出问题。后逐渐转换为workerman,直接用GatewayWorker开启独立的websocket来配合着laravel框架一起用,解决了之前许多的websocket方面的问题,完美实现了单点登录,客服服务、聊天室、实时数据更新等应用场景。有相关需求的可以看我的demo(https://element.wmhello.cn)