problem
Look at the following code $word = ' HELLO '; $conf = Array (' IP ' => ' 10.1.146.133 ', ' Port ' =>2001), array (' IP ' => ' 10.1.146.133 ', ' Port ' =>2002)); function Udpget ($word, $ip, $port) {$sock = Socket_create (Af_inet, Sock_dgram, SOL_UDP); Socket_set_option ($sock, Sol_so Cket, So_sndtimeo, Array (' sec ' =>2, ' usec ' =>0)); Socket_set_option ($sock, Sol_socket, So_rcvtimeo, Array (' sec ' =>2, ' usec ' =>0)); Socket_sendto ($sock, $word, strlen ($word), 0x100, $ip, $port); Socket_recvfrom ($sock, $result, 8192, 0, $host, $port); Socket_close ($sock); return $result; For ($i =0 $i <2; $i + +) {$res = Udpget ($word, $conf [$i] [' IP '], $conf [$i] [' Port ']); Var_dump ($res); is to send and receive data continuously with UPD to two servers (to illustrate the problem, the server here uses the simplest return logic), if all processes are normal, the client will receive two times ' HELLO '. But what if the service is out of the question? At present, the client's timeout is 2 seconds, assuming 2001 port over 3 seconds to send data, and 2002 ports can not serve, guess what the result will be? "Two A null! "It should be the answer intuitively. If you think so, congratulations, wrong answer.
The actual answer is:The NULL string (5) "HELLO" Analysis uses the Tcpdump grab package to get the following results (133 for server, 163 for client, client PHP version 5.3.1,linux kernel 2.6.16) 12:01:39.014658 IP 10.1.146.163.40678 > 10.1.146.133.2001:udp, length 5 12:01:41.015121 IP 10.1.146.163.40678 > 10.1.146.133.2002:ud P, length 5 12:01:42.016103 IP 10.1.146.133.2001 > 10.1.146.163.40678:udp, length 52 requests should use a different temporary port to send and receive, but from the results of the grab packet, the client though into Row two times socket_create, but in practice, but use the same temporary port (40678) send and receive data! This causes the second request to receive the first requested back package. It feels like a system bug, and from the experiment it turns out that this problem only exists in some systems, such as the Linux kernel 2.6.32+php5.2.3.
SolveEach time you specify a socket port, send and receive. As shown in the red code below. $sock = Socket_create (Af_inet, Sock_dgram, SOL_UDP); $sendPort = rand (10240, 60000); Socket_bind ($sock, ' 10.1.146.163′, $sendPort); Socket_set_option ($sock, Sol_socket, So_sndtimeo, Array (' sec ' =>2, ' usec ' =>0)); Socket_set_option ($sock, Sol_socket, So_rcvtimeo, Array (' sec ' =>2, ' usec ' =>0)); Of course, Rand's ports are also likely to bump, but after all, this is not a very good chance to solve the problem to a large extent.