PHP fsockopen 长连接发送实现
具体实现代码如下所示:
<?php
// post.php
function Post($host, $port)
{
// $host="127.0.0.1";
// 建立网络连接
$conn = fsockopen($host, $port);
if (!$conn)
{
die("Con error");
}
// 循环执行5次数据发送
//
for($i = 0; $i < 5; $i++)
{
$data = "user_name=admin" . $i;
WriteData($conn, $host, $data);
echo $i . "<br>";
";
}
fclose($conn);
}
function WriteData($conn, $host, $data)
{
$header = "POST /test.php HTTP/1.1\r\n";
$header .= "Host : {$host}\r\n";
$header .= "Content-type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length:" . strlen($data) . "\r\n";
// 保持连接是关键步骤
$header .= "Connection: Keep-Alive\r\n\r\n";
$header .= "{$data}\r\n\r\n";
fwrite($conn, $header);
// 获取返回结果
// $result = '';
// while(!feof($conn))
//{
// $result .= fgets($conn, 128);
//}
// return $result;
}
Post('127.0.0.1', 80);
?> 服务端接收代码如下:
<?php
// test.php
$fp = fopen('result.txt', 'a');
$data = $_POST['user_name'] . " -- " . date('Y-m-d H:i:s') . "\r\n";
fwrite($fp, $data);
fclose($fp);
?>