標籤:world cti recv bst ror date sub 列印 style
服務端:
//伺服器資訊 $server = ‘udp://127.0.0.1:9998‘; //訊息結束符號 $msg_eof = "\n"; $socket = stream_socket_server($server, $errno, $errstr, STREAM_SERVER_BIND); if (!$socket) { die("$errstr ($errno)"); } do { //接收用戶端發來的資訊 $inMsg = stream_socket_recvfrom($socket, 1024, 0, $peer); //服務端列印出相關資訊 echo "Client : $peer\n"; echo "Receive : {$inMsg}"; //給用戶端發送資訊 $outMsg = substr($inMsg, 0, (strrpos($inMsg, $msg_eof))).‘ -- ‘.date("D M j H:i:s Y\r\n"); stream_socket_sendto($socket, $outMsg, 0, $peer); } while ($inMsg !== false);
用戶端:
function 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;
PHP socket通訊之UDP