This article illustrates the UDP communication method of PHP socket communication. Share to everyone for your reference. Specifically as follows:
1. Create a simple UDP server
Server information
$server = ' udp://127.0.0.1:9998 ';
Message end symbol
$msg _eof = "\ n";
$socket = Stream_socket_server ($server, $errno, $errstr, stream_server_bind);
if (! $socket) {
die ("$errstr ($errno)");
}
do {
//Receive client sent information
$INMSG = Stream_socket_recvfrom ($socket, 1024, 0, $peer);
The service side prints out the relevant information
echo "Client: $peer \ n";
echo "Receive: {$INMSG}";
Send message to client
$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);
2. Simple Client
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;
I hope this article will help you with your PHP program design.