php模拟socket一次连接,多次发送数据的实现
生活随笔
收集整理的這篇文章主要介紹了
php模拟socket一次连接,多次发送数据的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<?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";
//Keep-Alive是關鍵
$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);
?>
//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";
//Keep-Alive是關鍵
$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);
?>
轉自:csdn
轉載于:https://www.cnblogs.com/ccdc/archive/2011/07/24/2115162.html
總結
以上是生活随笔為你收集整理的php模拟socket一次连接,多次发送数据的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 聊一下我们团队的理念
- 下一篇: Object-C时间与字符串的转化 因多