服务器端脚本:
<?php
$host="127.0.0.1";
$port=1232;
set_time_limit(0);
//开启套接字监听过程
$socket=socket_create(AF_INET,SOCK_STREAM,6) or die("Could not create socket\n");
$result=socket_bind($socket,$host,$port) or die("Could not bind to socket\n");
$result=socket_listen($socket,3) or die("Could not set up socket listener\n");
//开启连接请求接受过程
//while(true){ //如果需要持续性监听,就在此开启死循环
$spawn=socket_accept($socket) or die("Could not accept incoming connection\n");
$input=socket_read($spawn,10240) or die("Could not read input\n");
$input=trim($input);
$output=$input ."\n";
socket_write($spawn,$output,strlen($output)) or die("Could not write output\n");
socket_close($spawn);
//}
socket_close($socket);
客户端脚本:
<?php
$host="127.0.0.1";
$port=1232;
$socket=socket_create(AF_INET,SOCK_STREAM,6) or die("Could not create socket\n");
$conn = socket_connect ($socket, $host, $port);//连接服务器
socket_write ($socket, 'wocao', 5);//传输数据
$output=socket_read($socket,10240) or die("Could not read input\n");
echo $output;
socket_close ($socket);