如何通过UDP将数据通过PHP发送到IP地址?

时间:2009-03-26 22:14:51

标签: php udp sockets

如何通过UDP将数据用PHP发送到IP地址?

如何在另一台计算机上恢复该数据?

<?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;
?>

此代码向“kik”发送一个程序,我可以在另一台计算机上读取它,但我怎样才能在浏览器中看到它?

4 个答案:

答案 0 :(得分:7)

我的PHP知识有点生疏,所以我一直在寻找一些好的指南和教程。这个PHP Sockets Made Easy看起来像是一个很好的入门指南。

编辑:我发布的原始文章没有详细介绍UDP,因此我删除了以前的代码。来自PHP Manual的文章提供了一些关于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);

?>

编辑#2 :这是PHP中套接字编程的另一个useful tutorial。它主要是TCP,但它确实包含了一个关于如何改变代码以使用UDP的部分。

答案 1 :(得分:1)

刚刚从我的一些工作代码中删除了这个代码片段



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

答案 2 :(得分:0)

我想你会发现PHP's socket reference是研究这个话题的好地方。

答案 3 :(得分:0)

<?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");
}
?>