创建文件 server.php 内容如下
<?php $filename = '/data/www/devil/tcp/server.txt'; $myfile = fopen($filename, "a+"); set_time_limit( 0 ); ob_implicit_flush(); $socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ); socket_bind( $socket, '192.168.1.94', 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; fwrite($myfile, $hear); if("bye\r\n"==$hear){ socket_shutdown($acpt); break; } usleep( 5000 ); } socket_close($socket); fclose($myfile); ?>
创建文件 client.php 内容如下
<?php $filename = '/data/www/devil/tcp/client.txt'; $myfile = fopen($filename, "a+"); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $con=socket_connect($socket,'192.168.1.94',11109); if(!$con){socket_close($socket);exit;} echo "Link\n"; while($con){ $hear=socket_read($socket,1024); echo $hear; fwrite($myfile, $hear); $words=fgets(STDIN); socket_write($socket,$words); if($words=="bye\r\n"){break;} usleep( 5000 ); } socket_shutdown($socket); socket_close($sock); fclose($myfile); ?>
文件创建好后,修改 $filename 变量相对应自己系统的地址,写测试数据
192.168.1.94 ip改成自己服务器的或者本机ip
php server.php php client.php 在 server.php 窗口输入 hello 回到 client.php 窗口可以马上看见 hello 当然在 client.php 窗口输入的内容在 server.php 窗口也可以马上看见
发表评论: