1、案例函数汇总
2、案例
通过socket创建udp服务,获取对端的ip和port信息。并进行打印
2.1、udp服务源码
/**
* Copyright(C) Iamasb
* @project : 3、workerman相关知识点
* @explain : 原生socket创建创建udp服务
* @filename : socket_udp.php
* @author : Iamasb
*/
// 创建udp
if (!($resource = socket_create(AF_INET,SOCK_DGRAM, SOL_UDP))) {
echo "socket create is error";
exit();
}
// 绑定本地ip和端口
if (!socket_bind($resource,'0.0.0.0','1235')) {
echo "socket bind is error";
exit();
}
// 设置端口复用
if (!socket_set_option($resource, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
exit;
}
// 循环
while (1) {
$from = '';
$port = 0;
// 接收数据
socket_recvfrom($resource, $buf, 1024, 0, $from, $port);
echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
// 往对端发送数据
socket_sendto($resource,'iamasb',strlen('iamasb'),0,$from,$port);
}
2.2、启动udp服务
3、测试
通过编写udp客户端进行测试
3.1、udp客户端代码
if (!($resource = socket_create(AF_INET,SOCK_DGRAM, SOL_UDP))) {
echo "socket create is error";
exit();
}
$msg = "Ping !";
$len = strlen($msg);
socket_sendto($resource, $msg, $len, 0, '127.0.0.1', 1235);
$from = '';
$port = 0;
socket_recvfrom($resource, $buf, 1024, 0, $from, $port);
echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
socket_close($resource);
3.2、执行udp客户端
此时udp服务端的打印结果如下