Receive response to UDP messages in PHP

0

Good morning! I have the following PHP code to send commands via UDP:

function sendPacket($packet, $ip, $port){
   $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
   socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, 1);
   $message = '';
   foreach ($packet as $chunk){   //Esto es porque se espera un array de bytes
       $message .= chr($chunk);
   }
   socket_sendto($socket, $message, strlen($message), 0, $ip, $port);
   socket_close($socket);
}

The packages I send are of the style:

const Ejemplo = array(0x12, 0x05, 0xb0);

The issue is that for certain commands, the receiver should send a response, an "OK", and I already gave a thousand laps and can not find the method to listen. I tried doing a connect / bind and using recvfrom, but nothing worked. I would need to find a way, using the previous function to send the command, to automatically listen to me to wait for the answer if there was one, at least for a limited time.

    
asked by Christian Barcelo 01.03.2017 в 18:09
source

1 answer

0

UDP is a very simple protocol that does not guarantee the reception of the message and therefore does not maintain the state of the connection. Since it does not require a negotiation to establish a connection, it seems to me that it is not necessary to use socket_connect .

In order to receive a response, it is necessary to assign to the socket an address and port of the machine where the code is executed using socket_bind . That is, you have to indicate in which direction and port you expect to receive the answers.

After sending the message with socket_sendto the code should wait a while to allow the message to reach the destination and send the response. After that wait, you would have to execute socket_recvfrom , probably with the flag MSG_DONTWAIT to avoid blocking in case the answer does not arrive (remember that UDP does not guarantee the reception of the messages).

Your code should determine the maximum waiting time and handle situations where no response is received.

    
answered by 01.03.2017 / 19:55
source