简体   繁体   English

PHP套接字客户端循环迭代

[英]PHP socket client in loop itertion

I want to implement a client socket in PHP. 我想在PHP中实现客户端套接字。

The socket type is TCP / IP and runs a full-duplex channel. 套接字类型为TCP / IP,并运行全双工通道。 The client must send requests to the server every second, so it must be run in a loop. 客户端必须每秒发送请求到服务器,因此必须循环运行。

Do I have to recreate and connect to the socket for each request? 是否必须为每个请求重新创建并连接到套接字? Or is it better to create and connect to the socket outside by the loop and then manage the communication? 还是通过循环创建并连接到外部套接字,然后管理通信更好?

<?php
   while (true) {
      //management of the pid here
      //create the socket
      $socket = socket_create (AF_INET, SOCK_STREAM, 0);
      //send the request
      $sent = socket_write ($socket, <query>, <length>);
      //get the answer
      $response = socket_read ($socket, 1024);
      //close the socket
      socket_shutdown ($socket, 2);
      usleep (500);/ / wait remote host
      socket_close ($socket);
      sleep (1);
   }
?>

I have already implemented the socket connection outside the loop and the management of requests inside. 我已经在循环外部实现了套接字连接,并在内部实现了请求管理。

But the connection remains active for a few minutes then returns an error on the endpoint connection. 但是连接保持活动状态几分钟,然后在端点连接上返回错误。

Is it necessary to use socket_bind in this situation? 在这种情况下是否需要使用socket_bind?

Thank you. 谢谢。

You should connect the socket once outside the loop, then use it for the entire application session. 您应该在循环外连接一次套接字,然后将其用于整个应用程序会话。 Disconnect the socket when the loop finishes. 循环结束后,断开插座。

创建套接字会消耗大量资源,并且由于您没有连接到多个点,因此应在循环外部创建套接字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM