一丶运行环境
这里我用的是 ContOS 7 aly 的服务器
PHP 8.0.16
Redis Redis 5.0.8
Nginx 1.12.2
二丶编写代码
通过Redis进行数据交互
在socket.php内进行和客户端根据业务逻辑进行数据的发送
在其他程序中进行数据的存储
socket.php
<?php
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'0.0.0.0',9999) or die('error');
socket_listen($socket,50);
$redis = new Redis();
//连接
$redis->connect('127.0.0.1', 6379);
//检测是否连接成功
while(true) {
$client = socket_accept($socket);
//创建子进程
$pid = pcntl_fork();
//父进程和子进程都会执行下面代码
if ($pid == -1) {
//print_r($pid);
//错误处理:创建子进程失败时返回-1.
die('could not fork');
} else if ($pid) {
//父进程会得到子进程号,所以这里是父进程执行的逻辑
//pcntl_wait($status); //等待子进程中断,防止子进程成为僵尸进程。
socket_close($client);
} else {
while (true) {
//读取客户端上传的数据
$buf = socket_read($client, 1024);
//因为上传的是JSon这里需要解码
$msg = json_decode($buf,true);
//判断数据是否为空
if($buf){
echo "\n客户端上传:";
print_r($msg);
//要返回的数据
$res = array();
//判断客户端上传的数据,根据数据返回不同的数据 这里domo简单 这里可以用switch case
if($buf['code']=='text1'){
$res = $redis->get('text1');
//同样下发要转码
$res = json_encode($res);
echo "\n服务器下发:";
print_r($res);
//发送
socket_write($client,$res);
}else{
$res = $redis->get('text1');
//同样下发要转码
$res = json_encode($res);
echo "\n服务器下发:";
print_r($res);
//发送
socket_write($client,$res);
}
}else{
echo "子进程不存在";
socket_close($client);
exit;
}
}
socket_close($client);
}
}