Home > Backend Development > PHP Tutorial > PHP Socket communication UDP communication example_PHP tutorial

PHP Socket communication UDP communication example_PHP tutorial

WBOY
Release: 2016-07-13 09:47:25
Original
1174 people have browsed it

UDP communication example of PHP's Socket communication

This article describes the UDP communication method of PHP's Socket communication. Share it with everyone for your reference. The details are as follows:

1. Create a simple UDP server

 ?

 18//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 information from the client

 $inMsg = stream_socket_recvfrom($socket, 1024, 0, $peer);

//The server prints out relevant information

echo "Client : $peern";

echo "Receive : {$inMsg}";

//Send information to the client

 $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. Simple client

 ?

 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;

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1025905.htmlTechArticle UDP Communication Example of PHP's Socket Communication This article describes the UDP communication method of PHP's Socket communication. Share it with everyone for your reference. The details are as follows: 1. Create a simple UDP server?...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template