Proper use of socket_select ()

What is the correct way to use socket_select in PHP to send and receive data?

I have a connection to a server that allows you to use TCP and UDP packets, I use both. As part of these connections, I send and receive packets on the same port, but a TCP packet will be sent to one port ( 29999 ), and UDP will be sent to another port ( 30000 ). The transfer type will be of type AF_INET . The IP address will be loopback 127.0.0.1 .

I have a lot of questions on how to create a socket connection in this scenario. For example, is it better to use socket_create_pair to connect, or use only socket_create and then socket_connect and then do socket_select ?

It is likely that no data will be sent from the server to the client, and the client must maintain a connection. This will be done using the timeout function in the socket_select call. If no data is sent within the time limit, the socket_select function will be broken, and then the saved packet can be sent. The following script belongs to the client.

 // Create $TCP = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $UDP = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); // Misc $isAlive = TRUE; $UDPPort = 30000; define('ISP_ISI', 1); // Connect socket_connect($TCP, '127.0.0.1', 29999); socket_connect($UDP, '127.0.0.1', $UDPPort); // Construct Parameters $recv = array($TCP, $UDP); $null = NULL; // Make The Packet to Send. $packet = pack('CCCxSSxCSa16a16', 44, ISP_ISI, 1, $UDPPort, 0, '!', 0, 'AdminPass', 'SocketSelect'); // Send ISI (InSim Init) Packet socket_write($TCP, $packet); /* Main Program Loop */ while ($isAlive == TRUE) { // Socket Select $sock = socket_select($recv, $null, $null, 5); // Check Status if ($sock === FALSE) $isAlive = FALSE; # Error else if ($sock > 0) # How does one check to find what socket changed? else # Something else happed, don't know what as it not in the documentation, Could this be our timeout getting tripped? } 
+4
source share
1 answer

I'm a little confused - it looks like you are trying to deal with asynchronous requests coming through 2 sockets, but both of them act as clients? This is a very unusual scenario. To try and implement them using different protocols (tcp and udp) is even weirder (H323 VOIP is the only application that I know it does). A quick google suggests that you are trying to write a client for LFS - but why do you need both the TCP and UDP client? (BTW publishes the appropriate PHP client code on its Wiki at http://en.lfsmanual.net )

A socket that has data waiting to be read will be in the $ recv array after calling socket_select () (i.e., the array is clipped and must be restarted before the next iteration of socket_select ()).

If socket_select returns 0, this means that the sockets are not blocked, and none of them has data available.

NTN

FROM.

+1
source

Source: https://habr.com/ru/post/1306222/


All Articles