gpt4 book ai didi

java - 简单的 PHP NAT 穿透服务器脚本

转载 作者:行者123 更新时间:2023-12-01 06:20:02 26 4
gpt4 key购买 nike

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

对于初学者来说,我想测试主服务器和 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 数据包的内容写入输出文本文件。谁能帮帮我吗?

最佳答案

enter image description here

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

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

关于java - 简单的 PHP NAT 穿透服务器脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com