Apr
08
2012
socket简单交互
服务端
server.php
<?php set_time_limit ( 0 ); $host = "127.0.0.1"; $port = 2046; $socket = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP ) or die ( "Could not create socket</br>\n" ); // 创建一个Socket $result = socket_bind ( $socket, $host, $port ) or die ( "Could not bind tosocket</br>\n" ); //绑定Socket到端口 $result = socket_listen ( $socket, 3 ) or die ( "Could not set up socket listener</br>\n" ); // 开始监听连接 $spawn = socket_accept ( $socket ) or die ( "Could not accept incoming connection</br>\n" ); // 处理通信 $input = socket_read ( $spawn, 1024 ) or die ( "Could not read input</br>\n" ); // 数据传送 获得客户端的输入 $input = trim ( $input ); if (! empty ( $input )) { if ($input == 'time') { $output = date ( "Y-m-d H:i:s" ) . "</br>\n"; //处理客户端输入并返回结果 } else { $output = "input error </br>\n"; //处理客户端输入并返回结果 } $Send = socket_write ( $spawn, $output, strlen ( $output ) ) or die ( "Could not write output</br>\n" ); // 数据传送 向客户端写入返回结果 echo 'input:', $input, "</br>\n"; echo "output:", $output, "</br>\n"; var_dump ( $Send ); } /*while ( @$buffer = socket_read ( $socket, 1024, PHP_NORMAL_READ ) ) { echo "Data sent was: time</br>\nResponse was:" . $buffer . "</br>\n"; }*/ // 关闭sockets socket_close ( $spawn ); socket_close ( $socket ); exit (); ?>
客户端
client.php
<?php set_time_limit ( 0 ); $host = "127.0.0.1"; $port = 2046; $socket = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP ) or die ( "Could not create socket</br>\n" ); // 创建一个Socket $connection = @ socket_connect ( $socket, $host, $port ) or die ( "Could not connet server</br>\n" ); // 连接 socket_write ( $socket, "time" ) or die ( "Write failed</br>\n" ); // 数据传送 向服务器发送消息 while ( @$buffer = socket_read ( $socket, 1024, PHP_NORMAL_READ ) ) { echo "Data sent was: time</br>\nResponse was:" . $buffer . "</br>\n"; } socket_close ( $socket ); ?>
最活跃的读者