gpt4 book ai didi

java - 如何连接局域网 (LAN) 之外的 DatagramSocket 服务器和客户端?

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

我能够在局域网 (LAN) 内连接 DatagramSocket 服务器和客户端,但无法在局域网之外连接。

这是我的代码:

GameServer 类:

public class GameServer extends Thread {

private DatagramSocket socket;

public GameServer() {
try {
this.socket = new DatagramSocket(7081,InetAddress.getByName("0.0.0.0"));
} catch (Exception e) {
e.printStackTrace();
}
}

public void run() {
while (true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
if(new String(packet.getData()).trim().equalsIgnoreCase("ping")){
sendData("pong".getBytes(),packet.getAddress(),packet.getPort());
}
System.out.println(new String(packet.getData()));
} catch (IOException e) {
e.printStackTrace();
}
}
}


public void sendData(byte[] data, InetAddress ipAddress, int port) {

DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
try {
this.socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}

}

GameClient 类:

public class GameClient extends Thread {

private InetAddress ipAddress;
private DatagramSocket socket;

public GameClient(String ipAddress) {
try {
this.socket = new DatagramSocket();
this.ipAddress = InetAddress.getByName(ipAddress);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}

public void run() {
while (true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
System.out.println(new String(packet.getData()));
} catch (IOException e) {
e.printStackTrace();
}
}
}


public void sendData(byte[] data) {

DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 7081);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}

}

RunClient 类:

public class RunClient {
public static void main(String[] args) {
GameClient client = new GameClient("/*Here is my external ip address*/"); //If i am running this for LAN then 192.168.1.67 and localhost work
client.start();
client.sendData("ping".getBytes());
}
}

RunServer 类:

public class RunServer {
public static void main(String[] args) {
GameServer server = new GameServer();
server.start();
}
}

这是我的端口转发配置:

Here are my port forwarding configurations

一些附加信息:
我的本地 IP 地址是 192.168.1.67
我使用的端口是7081
当我在 http://www.canyouseeme.org 检查我的 IP 和端口时它给了我以下错误:

Error: I could not see your service on "my external ip" on port (7081)

最佳答案

我没有发现您的代码有任何问题。该站点 ( http://www.canyouseeme.org ) 必须尝试使用​​ TCP 而不是 UDP。

关于java - 如何连接局域网 (LAN) 之外的 DatagramSocket 服务器和客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233415/

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