继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

php创建udp server client demo

慕虎7371278
关注TA
已关注
手记 1125
粉丝 201
获赞 871

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

server

<?phpnamespace 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);
   }

}
<?phpnamespace 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);
    }

}

说明

webp

udp server

webp

udp client

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

  • udp 通信没有经过三次握手,是不可靠的通信,应用场景应该 充分考量

  • 我用来建立一个日志收集server 所有系统统一往这个server上发送日志



作者:麦田348462402
链接:https://www.jianshu.com/p/097463d08664


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP