# WebSocketServer.php 后端核心服务,监听端口,接收数据,发送数据
## 1、监听多端口
~~~
//监听多端口,监听支付页面传过来的数据
$http = $this->server->listen($this->host, 9999, SWOOLE_SOCK_TCP);
$http->on("request", [$this, 'onRequest']);
public function onRequest($request, $response) {
$data = $request->post;
//协程redis
//将数据存入redis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
if ($data) {
foreach ($data as $v) {
$redis->lPush("dy", $v);
}
}
}
~~~
## 2、监听客户端连接事件
~~~
//监听连接打开事件
$this->server->on("open", [$this, 'onOpen']);
public function onOpen($ws, $request) {
echo "connestion open : {$request->fd}".PHP_EOL;
//客户端首次连接后端,需要将已经购买过的票发送给客户端,提示已经购买过
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$data = $redis->lRange("dy", 0, -1);
if ($data) {
foreach ($ws->connections as $fd) {
$ws->push($fd, json_encode($data));
}
}
}
~~~
## 3、主动发送消息给客户端
~~~
//监听WebSocket消息事件
$this->server->on("message", [$this, 'onMessage']);
//付款之后,通知所有人我已经买了这些票了
public function onMessage($ws, $frame) {
if ($frame->data == "success") {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
//取出所有购买的数据
$data = $redis->lRange("dy", 0, -1);
//将数据发送给所有客户端
foreach ($ws->connections as $fd) {
$ws->push($fd, json_encode($data));
}
}
}
~~~