WebSocket

WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

修改配置文件MAIN_SERVER.SERVER_TYPEEASYSWOOLE_WEB_SOCKET_SERVER

EasySwooleEventmainServerCreate事件进行回调注册:

  1. public static function mainServerCreate(\EasySwoole\EasySwoole\Swoole\EventRegister $register)
  2. {
  3. $register->set($register::onOpen, function ($ws, $request) {
  4. var_dump($request->fd, $request->server);
  5. $ws->push($request->fd, "hello, welcome\n");
  6. });
  7. $register->set($register::onMessage, function (\Swoole\WebSocket\Server $server, \Swoole\WebSocket\Frame $frame) {
  8. echo "Message: {$frame->data}\n";
  9. $server->push($frame->fd, "server: {$frame->data}");
  10. });
  11. $register->set($register::onClose, function ($ws, $fd) {
  12. echo "client-{$fd} is closed\n";
  13. });
  14. }