时间:2021-07-01 10:21:17 帮助过:20人阅读
//server.php
set_time_limit(0);
// Set up our socket
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, '192.168.10.224', 50004);
socket_listen($socket,5);
// Initialize the buffer
$buffer = "";
while(true)
{
$run=file_get_contents("./run.txt");
if($run==0)break;
// Accept any connections coming in on this socket
$connection = socket_accept($socket);
printf("Socket 链接中\r\n");
// Check to see if there is anything in the buffer
if($buffer != "")
{
printf("写入开始 缓冲区内容发送..\r\n");
socket_write($connection, $buffer . "\r\n");
printf("写入结束 \r\n");
}
else
{
printf("缓冲区无数据\r\n");
}
// Get the input socket_read($connection, 1024)
while($data = socket_read($connection, 4096))
{
if($run==0)break;
$buffer = $data;
//写入客户端数据
file_put_contents("./txt.txt", json_encode($data)."\n",FILE_APPEND);
socket_write($connection, "Information Received\r\n");
printf("读结束 缓冲区内容: " . $buffer . "\r\n");
}
socket_close($connection);
printf("关闭 socket\r\n\r\n");
}
//命令行里 输入: php server.php
//client.php 直接浏览器访问
$stime = microtime(true);
$fp = stream_socket_client("tcp://192.168.10.224:50004", $errno, $errstr, 30,STREAM_CLIENT_CONNECT
------解决方案--------------------
STREAM_CLIENT_PERSISTENT);
if (!$fp) {
echo "$errstr ($errno)
\n";
} else {
fwrite($fp,$msg,mb_strlen($msg));
echo fread($fp, 4096)."\n";
fclose($fp);
}
$etime = microtime(true);
echo "Time: " . ($etime - $stime) . "n";
//我目前杀掉占用端口太麻烦,直接用文件控制退出 。run.txt 文件存 0或1