用 PHP 接收 UDP 包数据报

dsl*_*ter 6 php udp data-conversion packet

我正在使用 php 为 GPS 跟踪系统构建侦听服务器。GPS 通过 UDP 数据包发送数据,我可以通过运行以下脚本来显示数据。然而,实际数据以符号形式出现,所以我猜我错过了转换

    //Reduce errors
    error_reporting(~E_WARNING);

    //Create a UDP socket
    if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        die("Couldn't create socket: [$errorcode] $errormsg \n");
    }

    echo "Socket created \n";

    // Bind the source address
    if( !socket_bind($sock, "192.168.1.29" , 1731) )
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        die("Could not bind socket : [$errorcode] $errormsg \n");
    }

    echo "Socket bind OK \n";

    //Do some communication, this loop can handle multiple clients
    while(1)
    {
        echo "\n Waiting for data ... \n";

        //Receive some data
        $r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
        echo "$remote_ip : $remote_port -- " . $buf;

            //Send back the data to the client
        //socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port);

    }

    socket_close($sock);
Run Code Online (Sandbox Code Playgroud)

Gee*_*man 4

我以前没有使用 PHP 这样做过,但我的第一个猜测是您将返回一个二进制字符串,您需要将其转换为 ASCII(或您正在使用的任何字符集)。

看来您应该能够使用 PHP 的unpack来实现此目的。

如果不知道您要返回什么数据,则很难确切地知道提供包的格式。看起来 unpack 至少能够返回一个十进制值数组(假设您正在返回字符),然后您可以使用chr将其转换为 ASCII 。可能是这样的:

//Receive some data
$r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
//Convert to array of decimal values
$array = unpack("c*chars", $buf);
//Convert decimal values to ASCII characters:
$chr_array = array();
for ($i = 0; $i < count($array); $i++)
{
    $chr_array[] = chr($array[$i]);
}
Run Code Online (Sandbox Code Playgroud)

这取决于协议设计,您对二进制数据的解析需要有多复杂(也就是说,您只是发送字符串数据,还是整数和字符串的混合等......您需要相应地解析二进制数据)。

编辑:我已经更新了格式字符串以匹配无限数量的字符,使用数组元素名称“chars”按照此处列出的格式。

编辑:在代码示例中添加了一些基本的 ASCII 转换。