php udp client,php创建udp server client demo

作为无连接的通信协议,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);

}

}

说明

AAffA0nNPuCLAAAAAElFTkSuQmCC

udp server

AAffA0nNPuCLAAAAAElFTkSuQmCC

udp client

此案例代码为我自己构建的框架demaya上测试,以上为运行结果udp 通信没有经过三次握手,是不可靠的通信,应用场景应该 充分考量

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

作者:麦田348462402

链接:https://www.jianshu.com/p/097463d08664

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值