TCP长链接

EasySwoole支持自定义tcp长链接。

设置监听

在Event.php的beforeWorkerStart事件监听链接。

  1. $listener = $server->addlistener("0.0.0.0",9502,SWOOLE_TCP);
  2. //混合监听tcp时 要重新设置包解析规则 才不会被HTTP覆盖,且端口不能与HTTP SERVER一致 HTTP本身就是TCP
  3. $listener->set(array(
  4. "open_eof_check"=>false,
  5. "package_max_length"=>2048,
  6. ));
  7. $listener->on("connect",function(\swoole_server $server,$fd){
  8. Logger::getInstance()->console("client connect");
  9. });
  10. $listener->on("receive",function(\swoole_server $server,$fd,$from_id,$data){
  11. Logger::getInstance()->console("received data :".$data);
  12. $server->send($fd,"swoole ".$data ." at time: ".time());
  13. //模拟其他地方调用向该链接发送信息 $fd是关键,是一个数字,可以缓存在redis等其他地方
  14. AsyncTaskManager::getInstance()->add(function()use($fd){
  15. sleep(3);
  16. Server::getInstance()->getServer()->send($fd,"this is delay message"." at time: ".time());
  17. });
  18. });
  19. $listener->on("close",function (\swoole_server $server,$fd){
  20. Logger::getInstance()->console("client close");
  21. }
  22. );

启动服务:php server start 即可成功监听TCP。测试:

telnet 127.0.0.1 9502