donglun7151 2015-04-08 03:52
浏览 77
已采纳

socket_write:如何在不关闭连接的情况下发送多个数据包?

I have this code:

$requestCount = 0;
$maxRequestCount = 10;

$ip = "192.168.0.100";
$port = 10000;

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connect = socket_connect($socket, $ip, $port);

while(true){
    if($requestCount == $maxRequestCount){break;}

    $write = socket_write($socket, $getHTTP, strlen($getHTTP));
    echo "Sending TCP message... OK (lenght = $write).<br>";

    $out = '';
    while($out = socket_read($socket, 65536)){echo "Reading response... OK (lenght = ". strlen($out).")<br>";}

    echo "<br>";

    usleep(100);
    $requestCount++;
}

socket_close($socket);

When the first request is made the connection is already closed (FYN, ACK). How do i send 10 packets and then the connection is closed?

enter image description here

  • 写回答

3条回答 默认 最新

  • dongshi2836 2015-04-08 05:30
    关注

    You can't. Just like a real-world conversation, there is no way to force somebody who isn't interested to keep listening. In the same way, you can't stop the computer on the other end of your socket from closing it.

    Judging from variable names in your code, it looks like you're sending HTTP requests (just on a different port). HTTP servers have the option of closing the connection after they respond to the first request they get in that connection. That's what appears to be happening here. You will have to create a new socket and reconnect to send each request.

    Another note: TCP doesn't have "packets". It is a stream oriented connection. I know that sounds like a pedantic difference, but it doesn't make sense to ask how you would "send multiple packets without closing the connection", because you don't get to control how TCP sends your messages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?