<?php
//服务器信息
$server = ‘udp://127.0.0.1:7002‘;
//----UDP Server
$msgEof = "\n";
$socket = stream_socket_server($server, $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
die($errstr.$errno);
}
do {
//接收客户端发来的信息
$inMsg = stream_socket_recvfrom($socket, 2048, 0, $peer);
//服务端打印出相关信息
//echo "Client : $peer\n";
//echo "Receive : {$inMsg}";
$inMsg = $inMsg . date(‘Y-m-d H:i:s‘);
//给客户端发送信息
file_put_contents("./tsrv.log", $inMsg, FILE_APPEND);
$outMsg = substr($inMsg, 0, (strrpos($inMsg, $msgEof))).‘|date:‘.date("Y-m-d H:i:s"."\n");
stream_socket_sendto($socket, $outMsg, 0, $peer);
} while ($inMsg !== false);
//----UDP client
function udpGet($sendMsg = ‘‘, $ip = ‘127.0.0.1‘, $port = ‘7001‘){
$handle = stream_socket_client("udp://{$ip}:{$port}", $errno, $errstr);
if( !$handle ){
die("ERROR: {$errno} - {$errstr}\n");
}
fwrite($handle, $sendMsg."\n");
$result = fread($handle, 1024);
fclose($handle);
return $result;
}
$result = udpGet(‘Hello World‘);
echo $result;
~