1.在/web/tool/demo/server下新建ws.php
```
<?php
class Ws {
CONST HOST = "0.0.0.0";
CONST PORT = 9501;
public $ws = null;
public function __construct() {
$this->ws = new swoole_websocket_server("0.0.0.0", 9501);
$this->ws->on("open", [$this, 'onOpen']);
$this->ws->on("message", [$this, 'onMessage']);
$this->ws->on("close", [$this, 'onClose']);
$this->ws->start();
}
/**
* 监听ws连接事件
* @param $ws
* @param $request
*/
public function onOpen($ws, $request) {
var_dump($request->fd);
}
/**
* 监听ws消息事件
* @param $ws
* @param $frame
*/
public function onMessage($ws, $frame) {
echo "ser-push-message:{$frame->data}\n";
$ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
}
/**
* close
* @param $ws
* @param $fd
*/
public function onClose($ws, $fd) {
echo "clientid:{$fd}关闭\n";
}
}
$obj = new Ws();
```
1.启动ws.php(websocket服务9501端口)
![](https://img.kancloud.cn/b3/43/b3436410460217bc72427c8513b1df50_528x64.png)
2.新建终端启动http_server.php(http服务9503端口)
![](https://img.kancloud.cn/3b/80/3b8021403393e8ad76dcb2f7de1a833f_579x69.png)
测试
![](https://img.kancloud.cn/ee/75/ee751798a3986574c37318e63d55a0ab_1555x338.png)