服务端
$ip = "127.0.0.1";
$port = "11100";
set_time_limit(0);//设置一个脚本的执行时间为无限长
echo '开始创建端口号为11100的端口'.chr(10);
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);//创建socket连接
if ($socket === false) {
echo "socket_create() failed:reason:" . socket_strerror(socket_last_error()) . "\n";
}
$ok = socket_bind($socket, $ip, $port);//绑定socket
if ($ok === false) {
echo "socket_bind() failed:reason:" . socket_strerror(socket_last_error($socket));
}
while (true) {
$from = "127.0.0.1";
$from_port = "11100";
$receiveData = socket_recvfrom($socket, $buf, 1024, 0, $from, $from_port);
//analysisData($receiveData, $buf, $from, $port);
echo '接收到的字符串为:'.$buf.'------字符串长度为:'.$receiveData.chr(10);
usleep(1000);//延迟代码执行若干微秒
}
客户端
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$msg = '皮卡丘';
$len = strlen($msg);
socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 11100);
socket_close($sock);
echo $msg.'------发送完了'
运行结果
[root@iZ28mhfkaunZ img]# /usr/local/web/fastphp/bin/php ./socketserver.php
开始创建端口号为11100的端口
接收到的字符串为:皮卡丘------字符串长度为:9