示例代码 - UDP命令解析

优质
小牛编辑
138浏览
2023-12-01

与TCP命令解析同理,直接上代码

解析器

  1. namespace AppSock;
  2. use CoreComponentSocketAbstractInterfaceAbstractClient;
  3. use CoreComponentSocketAbstractInterfaceAbstractCommandParser;
  4. use CoreComponentSocketCommonCommand;
  5. class Parser extends AbstractCommandParser
  6. {
  7. function parser(Command $result, AbstractClient $client, $rawData)
  8. {
  9. // TODO: Implement parser() method.
  10. $data = trim($rawData);
  11. $data = explode(',',$data);
  12. $result->setCommand(array_shift($data));
  13. $result->setMessage(array_shift($data));
  14. }
  15. }

命令注册

  1. namespace AppSock;
  2. use CoreComponentLogger;
  3. use CoreComponentSocketAbstractInterfaceAbstractCommandRegister;
  4. use CoreComponentSocketClientUdpClient;
  5. use CoreComponentSocketCommonCommand;
  6. use CoreComponentSocketCommonCommandList;
  7. use CoreComponentSocketResponse;
  8. use CoreSwooleAsyncTaskManager;
  9. class Register extends AbstractCommandRegister
  10. {
  11. function register(CommandList $commandList)
  12. {
  13. // TODO: Implement register() method.
  14. $commandList->addCommandHandler('hello',function (Command $request,UdpClient $client){
  15. $message = $request->getMessage();
  16. Logger::getInstance()->console('message is '.$message,false);
  17. AsyncTaskManager::getInstance()->add(function ()use($client){
  18. sleep(2);
  19. Response::response($client,"this is delay message for hellon");
  20. });
  21. return "response for hellon";
  22. });
  23. $commandList->setDefaultHandler(function (){
  24. return "unkown commandn";
  25. });
  26. }
  27. }

注意,UDP的回调客户端类型是UdpClient

事件监听

  1. use AppSockParser;
  2. use AppSockRegister;
  3. use CoreComponentSocketDispatcher;
  4. function beforeWorkerStart(swoole_server $server)
  5. {
  6. // TODO: Implement beforeWorkerStart() method.
  7. $udp = $server->addlistener("0.0.0.0",9503,SWOOLE_UDP);
  8. //udp 请勿用receive事件
  9. $udp->on('packet',function(swoole_server $server, $data,$clientInfo){
  10. Dispatcher::getInstance(Register::class,Parser::class)->dispatchUDP($data,$clientInfo);
  11. });
  12. }

测试代码

  1. $client = new swoole_client(SWOOLE_SOCK_UDP);
  2. if (!$client->connect('127.0.0.1', 9503, -1))
  3. {
  4. exit("connect failed. Error: {$client->errCode}n");
  5. }
  6. $client->send("hellon");
  7. echo $client->recv();
  8. $client->close();