必备知识
pcntl库
pcntl_fork()
创建一个子进程,创建成功返回子进程的pid号, 创建失败返回-1
socket系列函数
socket_create(); 创建socket
socket_bind(); 为socket绑定ip和端口
socket_listen(); 监听socket
socket_connect(); 开启一个socket连接
socket_read(); 读取数据
socket_write(); 写入数据socket_accept();
service.php
<?php
set_time_limit(0);
// 通用变量
$ip = "127.0.0.1";
$port = 3378;
$maxLength = 8192;
// sockets
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$res = socket_bind($sock, $ip, $port);
$res = socket_listen($sock, 10);
// $msgsock = socket_accept($sock);
$pid = 0;
while(1) {
$msgsock = socket_accept($sock);
$pid = pcntl_fork();
if($pid == -1) {
die("could not fork");
} else if($pid) {
// 父进程
} else {
// 子进程
while(1) {
$buf = socket_read($msgsock, $maxLength);
$buf = strtoupper($buf);
socket_write($msgsock, $buf, strlen($buf));
}
}
}
socket_close($sock);
clinet.php
<?php
set_time_limit(0);
$ip = "127.0.0.1";
$port = 3378;
$maxLength = 8192;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, $ip, $port);
while(1) {
// socket_connect($sock, $ip, $port);
fwrite(STDOUT, "请输入传递的数据:");
$res = fgets(STDIN);
socket_write($sock, $res, strlen($res));
$rea = socket_read($sock, $maxLength);
echo $rea;
}
socket_close($sock);