您的当前位置:首页php创建udp server client demo

php创建udp server client demo

2024-12-12 来源:哗拓教育

作为无连接的通信协议,udp的开销要比tcp要小而且速度会更快

server

<?php

namespace App\Shell;

use demaya\Console\Shell;

class LogServer extends Shell
{

   protected $addr = '127.0.0.1';
   protected $port = 10000;

   public function start()
   {
       if (($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) == FALSE) {
           $errorcode = socket_last_error();
           $errormsg = socket_strerror($errorcode);
           $this->error("创建socekt失败: [$errorcode] $errormsg");
       }
       $this->success('socket 创建成功...');

       // 绑定到 ip 端口
       if (!socket_bind($socket, $this->addr, $this->port)) {
           $errorcode = socket_last_error();
           $errormsg = socket_strerror($errorcode);
           $this->error("bind socket失败: [$errorcode] $errormsg");
       }
       $this->success('socket bind成功...');
       while (true) {
           $this->info("Waiting for data ... \n");
           //Receive 
           $r = socket_recvfrom($socket, $buf, 512, 0, $remote_ip, $remote_port);
           $this->info("$remote_ip : $remote_port -- " . $buf);
           //Send back
           socket_sendto($socket, "OK " . $buf, 100, 0, $remote_ip, $remote_port);
       }
       socket_close($socket);
   }

}

<?php

namespace App\Shell;

use demaya\Console\Shell;

class LogClient extends Shell
{

    protected $addr = '127.0.0.1';
    protected $port = 10000;

    public function start()
    {
        if (($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) == FALSE) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            $this->error("创建socekt失败: [$errorcode] $errormsg");
        }
        $this->success('socket 创建成功...');
        while (true) {
            $input = $this->climate->input('Enter a message to send :');
            $input = $input->prompt();
            if (!socket_sendto($socket, $input, strlen($input), 0, $this->addr, $this->port)) {
                $errorcode = socket_last_error();
                $errormsg = socket_strerror($errorcode);
                $this->error("Could not send data: [$errorcode] $errormsg \n");
            }
            
            if (socket_recv($socket, $reply, 2045, MSG_WAITALL) === FALSE) {
                $errorcode = socket_last_error();
                $errormsg = socket_strerror($errorcode);
                $this->error("Could not receive data: [$errorcode] $errormsg \n");
            }

            $this->info("Reply : $reply");
        }
        socket_close($socket);
    }

}

说明

udp server udp client

此案例代码为我自己构建的框架demaya上测试,以上为运行结果

  • udp 通信没有经过三次握手,是不可靠的通信,应用场景应该 充分考量
  • 我用来建立一个日志收集server 所有系统统一往这个server上发送日志
显示全文