最近要用php的udp做一个服务端,但是发现按照网上找到upd做服务器的代码,老是不尽如人意,发现一直在循环输出同样的内容,
仔细分析了php的udp特点之后,发现php的udp栈在没收到新的内容时会一直驻留,经过多方面的考虑于是写了如下代码:
<?php error_reporting( E_ALL ); set_time_limit( 0 ); ob_implicit_flush(); if (!extension_loaded('sockets')) { die('The sockets extension is not loaded.'); } $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP ); if ( $socket === false ) { echo "socket_create() failed:reason:" . socket_strerror( socket_last_error() ) . "\n"; exit(0); } $name = '192.168.1.102'; $port = '11211'; $ok=socket_bind($socket, $name, $port); if ( $ok === false ) { echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) ); exit(0); } echo 'begin<br/>'; $bufa='';$bufb=''; do{ $from=''; if (!socket_set_block($socket)) die('Unable to set blocking mode for socket'); $len=socket_recvfrom( $socket, $bufa ,1024,0, $from,$port); if($bufa=='bye') break; if($bufa!=$bufb){ file_put_contents( 'aaa.txt',$len.' '.$bufa ,FILE_APPEND); echo ' '.$bufa;} $len=socket_recvfrom( $socket, $bufb,1024,0, $from,$port); if($bufb=='bye') break; if($bufa!=$bufb){ file_put_contents( 'aaa.txt',$len.' '.$bufb ,FILE_APPEND); echo ' '.$bufb;} } while (true); echo '<br/>end'; socket_close($socket); ?>
评论回复