Home  >  Article  >  Backend Development  >  PHP的Socket通信之UDP通信实例,phpsocketudp实例_PHP教程

PHP的Socket通信之UDP通信实例,phpsocketudp实例_PHP教程

WBOY
WBOYOriginal
2016-07-13 09:47:23804browse

PHP的Socket通信之UDP通信实例,phpsocketudp实例

本文实例讲述了PHP的Socket通信之UDP通信方法。分享给大家供大家参考。具体如下:

1.创建一简单的UDP服务器

//服务器信息 
$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);

2.简单的客户端

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程序设计有所帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1026048.htmlTechArticlePHP的Socket通信之UDP通信实例,phpsocketudp实例 本文实例讲述了PHP的Socket通信之UDP通信方法。分享给大家供大家参考。具体如下: 1.创建一简单...
Statement:
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