【问题标题】:Simple PHP NAT Punch Through Server Script简单的 PHP NAT 穿透服务器脚本
【发布时间】:2012-07-13 13:08:24
【问题描述】:

我正在尝试编写一个 PHP 脚本,它可以充当“主服务器”并促进两个 Java 游戏客户端之间的 P2P 连接。我正在使用一个允许主服务器端口访问的共享网络主机。

对于初学者,我想测试主服务器和 java 客户端之间的 UDP 套接字连接。这是我的 PHP 脚本,名为“masterServer.php”

<?php
error_reporting(E_ALL);
set_time_limit(40); // Allow script to execute for at most 40 seconds.
$myFile = "output.txt";
$fh = fopen($myFile, 'w');

if ($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))
{

if(socket_bind($socket,0, 2005))
{
    $clientAddress = 0;
    $clientPort = 0;
    fwrite($fh, "Start at: ".time());
    fwrite($fh, "Waiting for socket at ".time());
    if(socket_recvfrom($socket, &$udp_buff, 23, MSG_WAITALL, &$clientAddress, &$clientPort)) // BLOCKING METHOD
    {
        fwrite($fh, print_r($udp_buff, true));
    }
    else
    {
        echo(socket_strerror(socket_last_error()));
        die();
    }
}
else
{
    echo(socket_strerror(socket_last_error()));
    die();
}
}
else
{
echo(socket_strerror(socket_last_error()));
die();
}

fwrite($fh, "End at: ".time());
fclose($fh);
?>

我访问 masterServer.php 以使脚本运行,并在几秒钟内启动一个简单的 Java 应用程序,该应用程序应将 UDP 数据包发送到主服务器。以下是 Java 应用程序的代码:

package comm;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPSocket 
{
public static void main (String[] asdf)
{

    try 
    {

        String host = <SERVER ADDRESS>;
        int port = 2005;

        byte[] message = "Java Source and Support".getBytes();

        // Get the internet address of the specified host
        InetAddress address = InetAddress.getByName(host);

        // Initialize a datagram packet with data and address
        DatagramPacket packet = new DatagramPacket(message, message.length,
                address, port);

        // Create a datagram socket, send the packet through it, close it.
        DatagramSocket dsocket = new DatagramSocket();
        dsocket.send(packet);
        dsocket.close();

    } 
    catch (SocketException e)
    {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

据我了解,PHP 服务器没有收到 UDP 数据包。该脚本不会继续通过阻塞 socket_recvfrom() 方法,并且不会将 UDP 数据包的内容写入输出文本文件。谁能帮帮我?

【问题讨论】:

  • 这两个脚本是否在同一台机器上运行?顺便说一句,你的代码看起来不错。
  • 不,PHP 运行在共享 Web 服务器 (Bluehost) 上,而 java 运行在我的开发机器上
  • 尝试在同一台机器上运行两者,看看它是否有效。可能是防火墙问题。
  • 一定会尝试的。我是 UDP 套接字编程的新手,所以我想确保我至少在正确的轨道上。谢谢!

标签: java php p2p nat hole-punching


【解决方案1】:

由于共享主机在路由器和防火墙后面运行,因此您的套接字将侦听其未连接到互联网的内部 IP 地址“192.168.1.102”(如上图所示),因此它无法接收从外部发送的任何数据内部网络。

解决方案 由于您使用的是 UDP,因此您可以使用一种称为UDP Puch Holing 的流行方法,您可以使用该方法从 Internet 发送和接收数据。根据您的要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多