March 14, 2008
Socket To Me
Sockets are the building blocks of networking connections between computers. Today I want to go though how to create a UDP listener (or socket server) in PHP. I recently had to do this to receive GPS data from some black boxes, and had a hard time finding examples of this type of UDP socket server. First of we need to specify who/where this socket will be created for; the host and port.
Pick a port that is higher than 1024, those below that are reserved.
#!/usr/bin/php -q <?php $address = "0"; //glom onto all addresses $rport = "1228"; //receiving port
You should make $address = “127.0.0.1″ if you only want to allow connections on the localhost…
Create the socket and bind it to that host and port, inside an infinite loop.
while (true) { //create a loop in which to collect packets
/* create a socket in the AF_INET family,
using SOCK_DGRAM for udp connections */
$mysock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($mysock, $address, $rport);
$from = "";
$port = 0;
//use socket_recvfrom() to collect connecting host/port info
socket_recvfrom($mysock, $buf, 65535, 0, $from, $port);
In my case the GPS data was coming in as Comma Seperated Values (csv). So I’m doing a simple parse for that:
//---- code to parse my csv data into an array
$lines = split("\n", $buf);
$i = 0;
foreach ($lines as $line) {
$linevalues = explode(",", $line);
if (count($linevalues) > 1) {
$values[$i] = $linevalues;
} //end if
$i++;
} //end foreach
//---- code to parse my csv data into a multidimensional array
print_r($values); //print out the array
In my case I’m going to be inserting the values into a MySQL database, but putting a multidimensional array into a MySQL database has been covered elsewhere.
You could also echo out the host and port connecting to your socket.
echo "From remote address $from and remote port $port" . PHP_EOL; } //end while(true) socket_close($mysock); ?>