Home >Backend Development >PHP Tutorial >PHP simulates socket connection once and sends data multiple times.
代码如下:
//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."
";
}
fclose($conn);
}
function WriteData($conn,$host,$data)
{
$header = "POST /test.php HTTP/1.1rn";
$header.= "Host : {$host}rn";
$header.= "Content-type: application/x-www-form-urlencodedrn";
$header.= "Content-Length:".strlen($data)."rn";
//Keep-Alive是关键
$header.= "Connection: Keep-Alivernrn";
$header.= "{$data}rnrn";
fwrite($conn,$header);
//取结果
//$result = '';
//while(!feof($conn))
//{
// $result .= fgets($conn,128);
/