幸福日记

WebSocket服务端开发(九)-WebSocketServer类事件

WebSocketServer类支持以下事件:
onstarted:
服务器启动后触发,socket_listen成功执行后,服务器进入启动状态

onconnected:
与客户端建立连接完成后触发,此时连接已放入socket连接池中

onUpgradePartReceive:
当收到部分WebSocket握手时触发,仅当收到的握手包不完整时会触发该事件

onHandShakeFailure:
在握手失败后触发

onHandShakeSuccess:
握手成功后触发

ondisconnected:
关闭客户端连接后触发,此时还未将连接从socket连接池中移除,当disconnect函数的第二个参数slient为true时不触发该事件

onAfterRemoveSocket:
在移除socket连接后触发

onafterhealthcheck:
在健康检查完成后触发,默认该事件会断开不健康的连接

onerror:
遇到socket错误时触发

onshutdown:
服务器关闭时触发

  function onstarted($serverSocket) {
    if ($this->debug) {
      printf('Server start at %s', date('Y-m-d H:i:s') . "\n");
    }
  }

  function onconnected($socket) {
    if ($this->debug) {
      printf('Socket connect at %s-%s', date('Y-m-d H:i:s'), $socket . "\n");
    }
  }

  function onUpgradePartReceive($socketId) {
    if ($this->debug) {
      $buffer = $this->socketListMap[$socketId]['buffer'];
      printf('Receive Upgrade Part at %s-%s%s(%d bytes)' . "\n", date('Y-m-d H:i:s'), $socketId . "\n", $buffer, strlen($buffer));
    }
  }

  function onHandShakeFailure($socketId) {
    if ($this->debug) {
      printf('HandShake Failed at %s-%s', date('Y-m-d H:i:s'), $socketId . "\n");
    }
  }

  function onHandShakeSuccess($socketId) {
    if ($this->debug) {
      printf('HandShake Success at %s-%s', date('Y-m-d H:i:s'), $socketId . "\n");
    }
  }

  function ondisconnected($socketId) {
    if ($this->debug) {
      printf('Socket disconnect at %s-%s', date('Y-m-d H:i:s'), $socketId . "\n");
    }
  }

  function onAfterRemoveSocket($socketId) {
    if ($this->debug) {
      printf('[onAfterRemoveSocket]remove:' . $socketId . ',left:' . implode('|', array_keys($this->socketListMap)) . "\n");
    }
  }

  function onafterhealthcheck($unhealthyList) {
    foreach ($unhealthyList as $socketId) {
      $this->disconnect($socketId);
    }
  }

  function onerror($errCode, $socketId) {
    switch ($errCode) {
    case 10053:
      $this->disconnect($socketId);
      break;
    default:
      if ($this->debug) {
        echo 'Socket Error:' . $errorCode . "\n";
      }
      break;
    }
  }

  function onshutdown() {
    if ($this->debug) {
      printf('Server shutdown!');
    }
  }
退出移动版