UDP命令解析

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

解析器

  1. namespace App\Sock;
  2. use Core\Component\Socket\AbstractInterface\AbstractClient;
  3. use Core\Component\Socket\AbstractInterface\AbstractCommandParser;
  4. use Core\Component\Socket\Common\Command;
  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 App\Sock;
  2. use Core\Component\Logger;
  3. use Core\Component\Socket\AbstractInterface\AbstractCommandRegister;
  4. use Core\Component\Socket\Client\UdpClient;
  5. use Core\Component\Socket\Common\Command;
  6. use Core\Component\Socket\Common\CommandList;
  7. use Core\Component\Socket\Response;
  8. use Core\Swoole\AsyncTaskManager;
  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 hello\n");
  20. });
  21. return "response for hello\n";
  22. });
  23. $commandList->setDefaultHandler(function (){
  24. return "unkown command\n";
  25. });
  26. }
  27. }

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

事件监听

  1. use App\Sock\Parser;
  2. use App\Sock\Register;
  3. use Core\Component\Socket\Dispatcher;
  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("hello\n");
  7. echo $client->recv();
  8. $client->close();