How can I send data with PHP to an IP address via UDP?
How can I recive that data on the other computer?
<?php
$fp = pfsockopen( "udp://192.168.1.6", 9601, $errno, $errstr );
if (!$fp)
{
echo "ERROR: $errno - $errstr<br />\n";
}
socket_set_timeout ($fp, 10);
$write = fwrite( $fp, "kik" );
//$data .= fread($fp,9600);
//echo "$data<br>";
fclose($fp);
echo "<br>Connection closed ..<br>";
if (!$write) {
echo "error writing to port: 9600.<br/>";
next;
?>
This code sends the "kik" with a program I can read it on the another computer, but how can I see it in the browser?
My PHP knowledge is a bit rusty so I've been doing some searching trying to find some good guides and tutorials. This one PHP Sockets Made Easylooks like it will be a good starter guide for you.
Edit: The original article I posted did not go into great detail for UDP so I eliminated the previous code. The article from the PHP Manual has some more information specifically regarding UDP:
<?php
$socket = stream_socket_server("udp://127.0.0.1:1113", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
die("$errstr ($errno)");
}
do {
$pkt = stream_socket_recvfrom($socket, 1, 0, $peer);
echo "$peer\n";
stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer);
} while ($pkt !== false);
?>
Edit #2: Here is another useful tutorial for socket programming in PHP. It is mostly TCP but it does include a section on how to alter the code to use UDP instead.
Just pulled this snippet out of some working code I have
if (!socket_bind($sh, LISTENIP, LISTENPORT)) exit("Could not bind to socket");
while (TRUE) {
// $z = socket_recvfrom($sh, $data, 65535, 0, $connectip, $connectPort);
while(socket_recvfrom($sh, $data, 65535, 0, $connectip, $connectPort)) {
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else { #START ELSE COULD FORK
$PIDS[$pid] = $pid; //KEEP TRACK OF SPAWNED PIDS
if ($pid) {
//PARENT THREAD : $ch is a copy that we don't need in this thread
} else {
/** CHILD THREAD::BEGIN PROCESSING THE CONNECTION HERE! **/
include "include/child_thread.inc.php";
} //Child Thread
}//if-else-forked
/** CLEANUP THE CHILD PIDs HERE :: "Any system resources used by the child are freed." **/
foreach ($PIDS as $pid) pcntl_waitpid($pid,$status,WNOHANG);
$i++; //INCREASE CONNECTION COUNTER
}//While socket_accept
/** CLEANUP THE PARENT PIDS **/
foreach ($PIDS as $pid) {
$returnPid = pcntl_waitpid($pid,$status);
unset($PIDS[$pid]);
}
}//While True
I think you'll find that the PHP's socket reference is a good place to study on this topic.
<?php
$server_ip = '127.0.0.1';
$server_port = 43278;
$beat_period = 5;
$message = 'PyHB';
print "Sending heartbeat to IP $server_ip, port $server_port\n";
print "press Ctrl-C to stop\n";
if ($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) {
while (1) {
socket_sendto($socket, $message, strlen($message), 0, $server_ip, $server_port);
print "Time: " . date("%r") . "\n";
sleep($beat_period);
}
} else {
print("can't create socket\n");
}
?>