本文實例講述了php socket通訊(tcp/udp)方法。分享給大家參考,具體如下:
注意
1.在socket_bind的時候ip位址不能真回環位址如127.0.0.1
2.server.php後台跑起來的時候nohup php server.php > /
<?php //error_reporting( E_ALL ); set_time_limit( 0 ); ob_implicit_flush(); $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP ); if ( $socket === false ) { echo "socket_create() failed:reason:" . socket_strerror( socket_last_error() ) . "\n"; } $ok = socket_bind( $socket, '202.85.218.133', 11109 ); if ( $ok === false ) { echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) ); } while ( true ) { $from = ""; $port = 0; socket_recvfrom( $socket, $buf,1024, 0, $from, $port ); echo $buf; usleep( 1000 ); } ?>2) client.Smm
1) server.php
<?php $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); $msg = 'hello'; $len = strlen($msg); socket_sendto($sock, $msg, $len, 0, '202.85.218.133', 11109); socket_close($sock); ?>
2) client.php
<?php //error_reporting( E_ALL ); set_time_limit( 0 ); ob_implicit_flush(); $socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ); socket_bind( $socket, '192.168.2.143', 11109 ); socket_listen($socket); $acpt=socket_accept($socket); echo "Acpt!\n"; while ( $acpt ) { $words=fgets(STDIN); socket_write($acpt,$words); $hear=socket_read($acpt,1024); echo $hear; if("bye\r\n"==$hear){ socket_shutdown($acpt); break; } usleep( 1000 ); } socket_close($socket) ?>
希望本文所述對大家PHP程式設計有所幫助。
更多php socket通訊(tcp/udp)實例分析相關文章請關注PHP中文網!