使用PHP进行UDP Socket编程
本文主要是通过简单的例子介绍下UDP Socket编程.
1.UDP服务器
<?php //Reduce errors error_reporting(~E_WARNING); //Create a UDP socket if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; // Bind the source address if( !socket_bind($sock, "0.0.0.0" , 11300) ) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [$errorcode] $errormsg \n"); } echo "Socket bind OK \n"; //Do some communication, this loop can handle multiple clients while(1) { echo "Waiting for data ... \n"; //Receive some data $r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port); echo "$remote_ip : $remote_port -- " . $buf; //Send back the data to the client socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port); } socket_close($sock);
在Terminal运行:
$php socket_udp_server.php
Socket created
Socket bind OK
Waiting for data …
2.UDP客户端
<?php //Reduce errors error_reporting(~E_WARNING); $server = '127.0.0.1'; $port = 11300; if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; //Communication loop while(1) { //Take some input to send echo 'Enter a message to send : '; $input = fgets(STDIN); //Send the message to the server if( ! socket_sendto($sock, $input , strlen($input) , 0 , $server , $port)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not send data: [$errorcode] $errormsg \n"); } //Now receive reply from server and print it if(socket_recv ( $sock , $reply , 2045 , MSG_WAITALL ) === FALSE) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not receive data: [$errorcode] $errormsg \n"); } echo "Reply : $reply"; }
在Terminal运行客户端程序:
$php socket_udp_client.php
Socket created
Enter a message to send : udp testonly
Reply : OK udp testonly
Enter a message to send :
- 版权申明:此文如未标注转载均为本站原创,自由转载请表明出处《博瑞博客》。
- 本文网址:http://blog.neacn.com/PHP/80.html
- 上篇文章:php获取当前时间的毫秒数的方法
- 下篇文章:PHP的Socket通信之UDP篇