使用 PHP 进行套接字编程

发布于 2024-08-09 07:05:23 字数 510 浏览 2 评论 0原文

我正在通过套接字连接到远程网站。我期待来自远程站点的特定字符串“XXX”。收到字符串后,我想将“ACK”200 OK 响应发送回远程服务器。

这就是我到目前为止所拥有的(假设套接字成功打开); $fp 是指向套接字的资源(指针):

 while (!feof($fp)) {
   $data = fgets ($fp, 1024);
   if (strcmp("PASS",$data)==0) {
 // Send 200 OK 'ack' response to remote server
     $response = "HTTP/1.0 200 OK\r\n";
 fputs ($fp, $response);

     // Do additional processing here ...
   }
 }
 fclose($fp)

我不确定的是,在 (!feof()) while 循环中使用 fput 是否“合法”。如果上面的代码有什么问题,如果有人能指出(即如果可以写得更好),我将不胜感激。

I am connecting to a remote website via sockets. I am expecting a specific string 'XXX' from the remote site. Upon receipt of the string, I want to send back an 'ACK' 200 OK response back to the remote server.

This is what I have so far (assume socket successfully opened);
$fp is resource (pointer) to the socket:

 while (!feof($fp)) {
   $data = fgets ($fp, 1024);
   if (strcmp("PASS",$data)==0) {
 // Send 200 OK 'ack' response to remote server
     $response = "HTTP/1.0 200 OK\r\n";
 fputs ($fp, $response);

     // Do additional processing here ...
   }
 }
 fclose($fp)

What I am not sure about, is whether it is 'legal' to use fputs in the (!feof()) while loop. If there is anything wrong with the above code, I will be grateful if someone could point it out (i.e. if it could be written better).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏璃陌 2024-08-16 07:05:23

这看起来不错,但如果您要寻找的只是一个字符串,那么您也可以在找到它后立即跳出读取循环。

例如

while (!feof($fp)) {
   $data = fgets ($fp, 1024);
   if (strcmp("PASS",$data)==0) 
      break;
 }

$response = "HTTP/1.0 200 OK\r\n";
fputs ($fp, $response);

fclose($fp);

This looks fine, but if all you're looking for is one string you may as well break out of the read loop as soon as you've found it.

e.g.

while (!feof($fp)) {
   $data = fgets ($fp, 1024);
   if (strcmp("PASS",$data)==0) 
      break;
 }

$response = "HTTP/1.0 200 OK\r\n";
fputs ($fp, $response);

fclose($fp);
幸福还没到 2024-08-16 07:05:23

如果循环中的“附加处理”意味着您将从套接字句柄中读取更多内容,那么我想说您必须在发回某些内容之前完成读取其所有响应。

如何在该循环中设置一个状态来指示您在处理完服务器对您的响应后将发回 200。然后,在完成循环后,fputs 返回响应。

哦,前面的答案说了同样的事情,只不过您可能不想仅仅因为找到“PASS”就打破循环。

If your "additional processing" in the loop means you'll be reading more from the socket handle, then I would say you have to finish reading in all of its response before you send something back.

How about setting a status in that loop to indicate you're going to send back the 200 when you're finished processing that server's response to you. Then after you're all done with the loop, fputs back the response.

Oh, the previous answer says about the same thing except you might not want to be breaking the loop just because you found "PASS".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文