服务端
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,0,95012) or die( 'server bind fail:' . socket_strerror(socket_last_error()));
socket_listen($socket,5);
$child = 0; //初始化子进程数
while(true){
$client = socket_accept($socket);
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
socket_close($client);
$child++;
if($child >= 3){ //假设最大进程数为3
pcntl_wait($status); //等待上一个进程结束
$child--;
}
} else {
while (true) {
$buf = socket_read($client, 1024);
echo $buf.PHP_EOL;
if ($buf === FALSE || strcmp($buf, '') == 0) {
$code = socket_last_error($client);
socket_clear_error($client);
if ($code == SOCKET_EAGAIN) {
// Nothing to read from non-blocking socket, try again later...
echo '无法从非阻塞套接字读取,请稍后再试..。';
} else {
// Connection most likely closed, especially if $code is '0'
echo '连接很可能已关闭,特别是当 $code 为“0”时';
socket_close($client);
exit;//关闭子进程
}
}else {
if (preg_match('/sleep/i', $buf)) {
sleep(10);
$html = 'HTTP/1.1 200 OK' . PHP_EOL
. 'Content-Type: text/html;charset=utf-8' . PHP_EOL . PHP_EOL;
socket_write($client, $html);
socket_write($client, "this is server,休克了10秒,模拟很繁忙的样子");
} else {
socket_write($client, "this is server");
}
}
}
}
}
socket_close($socket);
客户端
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_connect($socket, '127.0.0.1', 95012);
while (true){
fwrite(STDOUT, '请输入消息:');
$in = fgets(STDIN);
//向服务端发送消息
socket_write($socket,$in);
//读取服务端消息
$msg = socket_read($socket,1024);
echo $msg.PHP_EOL;
}
socket_close($socket);
本文学习优化来源:https://blog.csdn.net/github_26672553/article/details/54582030