Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php作为C++;服务器_Php_C++_Sockets - Fatal编程技术网

使用php作为C++;服务器

使用php作为C++;服务器,php,c++,sockets,Php,C++,Sockets,我正面临一个奇怪的问题 我编写了一个C++的小服务器,它将文件以二进制格式存储在文件中。 我用telnet成功地测试了它 telnet 127.0.0.1 1234 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. store 1 1 5 1 store 1 1 5 2 服务器上的输出现在是 Command : store 1 1 5 1 Command : store 1 1 5 2 因为我们将使用p

我正面临一个奇怪的问题

我编写了一个C++的小服务器,它将文件以二进制格式存储在文件中。 我用telnet成功地测试了它

telnet 127.0.0.1 1234
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
store 1 1 5 1
store 1 1 5 2
服务器上的输出现在是

Command : store 1 1 5 1
Command : store 1 1 5 2
因为我们将使用php来存储这些信息,所以我编写了一个小php脚本,它将向我们的服务器发送10个命令

<?php

    $socket = socket_create(AF_INET,SOCK_STREAM,0);
    socket_connect($socket,"127.0.0.1",1234);

    for($i = 0;$i < 10;$i++){

        $command = "store 1 $i 5 1\r\n";

        echo $command;

        socket_write($socket,$command,strlen($command));

    }

    socket_close($socket);

?>
无法识别该\r\n文件。在四处搜索之后,我发现通过在socket_write函数之后添加一个usleep(10000),它实际上可以工作

我试图避免使用此解决方法,因此我必须回答以下问题:

为什么usleep要修复它? 没有usleep我怎么办


谢谢你的阅读

> P>我们必须看到你的C++服务器,但是我怀疑你在那里分析数据不正确。 TCP是一种流协议,在该协议中,数据包中的数据没有边界。因此,当您发送多个“存储”命令时,它们可能都出现在同一个TCP数据包中。然后,当您调用
recv()
时,可能会得到多个“存储”。然而,由于时间的原因,以及telnet可能正在发送它自己的数据包中的每一行,对
recv()
的每次调用都可能检索一个“存储”命令

当您将usleep放入时,实际上是在延迟排队等待更多数据,TCP放弃了等待,并自行将“存储”发送到数据包中

在您的服务器中,您必须

  • 期望从
    recv()检索多个“存储区”
  • 期望一个“存储”被分割到多个
    recv()
    调用中
  • usleep
    是一种黑客行为,可能并不总是有效

    Command : store 1 0 5 1store 1 1 5 1store 1 2 5 1store 1 3 5 1store 1 4 5 1store 1 5 5 1store 1 6 5 1store 1 7 5 1store 1 8 5 1store 1 9 5 1