1、案例函数汇总
2、案例
创建一个udp服务,接收客户端的请求。并打印相应的信息
2.1、udp服务代码
<?php
/**
* Copyright (C) Iamasb
* @project : 3、workerman相关知识点
* @explain : stream创建udp服务
* @filename : 36、stream创建udp服务.php
* @author : xiaobei 2801616735@qq.com
*/
error_reporting(0);
$local = "udp://0.0.0.0:1235";
$main = stream_socket_server($local,$errno,$errstr,STREAM_SERVER_BIND );
if (!$main) {
echo "error->",$errno,' errstr->',$errstr,PHP_EOL;
exit;
}
$start = "hello world.";
while (true) {
$string = stream_socket_recvfrom($main,1024,0,$peer);
echo "receive->",$string," from->",$peer,PHP_EOL;
stream_socket_sendto($main,$start,0,$peer);
$string = stream_socket_recvfrom($main,1024,0,$peer);
echo "receive->",$string," from->",$peer,PHP_EOL;
stream_socket_sendto($main,$start,0,$peer);
}
2.2、启动udp服务
3、测试
编写udp客户端
3.1、编写udp客户端
<?php
/**
* Copyright (C) Iamasb
* @project : 3、workerman相关知识点
* @explain : stream创建udp客户端
* @filename : 37、stream创建udp客户端.php
* @author : xiaobei 2801616735@qq.com
*/
error_reporting(0);
$local = "udp://127.0.0.1:1235";
$client = stream_socket_client($local,$errno,$errstr);
if (!$client) {
echo "error->",$errno,'-->',$errstr,PHP_EOL;
exit;
}
$remoteIp = stream_socket_get_name($client,true);
echo "remoteIp->".$remoteIp,PHP_EOL;
// 读写方式1
$string = "i am a sb.";
fwrite($client,$string);
//echo fread($client,1024);
// 读写方式2
echo stream_socket_recvfrom($client,1024,0,$peer);
stream_socket_sendto($client,"hahah",0,$peer);
fclose($client);
3.2、测试结果