- 相關(guān)推薦
PHP的Socket通信之UDP通信實(shí)例
PHP的Socket通信之UDP通信的方法,你懂嗎?以下是百分網(wǎng)小編分享給大家,供大家參考。
1.創(chuàng)建一簡(jiǎn)單的UDP服務(wù)器
18//服務(wù)器信息
$server = 'udp://127.0.0.1:9998';
//消息結(jié)束符號(hào)
$msg_eof = "n";
$socket = stream_socket_server($server, $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
die("$errstr ($errno)");
}
do {
//接收客戶端發(fā)來的信息
$inMsg = stream_socket_recvfrom($socket, 1024, 0, $peer);
//服務(wù)端打印出相關(guān)信息
echo "Client : $peern";
echo "Receive : {$inMsg}";
//給客戶端發(fā)送信息
$outMsg = substr($inMsg, 0, (strrpos($inMsg, $msg_eof))).' -- '.date("D M j H:i:s Yrn");
stream_socket_sendto($socket, $outMsg, 0, $peer);
} while ($inMsg !== false);
2.簡(jiǎn)單的客戶端
?
12function udpGet($sendMsg = '', $ip = '127.0.0.1', $port = '9998'){
$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;
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。
【PHP的Socket通信之UDP通信實(shí)例】相關(guān)文章:
PHP多線程編程之管道通信實(shí)例07-28
Java網(wǎng)絡(luò)基礎(chǔ)和Socket通信基礎(chǔ)04-27
PHP curl之操作實(shí)例01-14
php之readdir函數(shù)用法實(shí)例02-07
PHP Socket編程過程07-19
PHP關(guān)鍵特性之命名空間實(shí)例02-12
php畫圖實(shí)例07-16
php中的socket框架性能分析07-17