我可以将我的DatagramSocket服务器和客户端连接到局域网(LAN)内,但不能在它之外。
这是我的代码:
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();
}
}
这是我的端口转发配置:
一些其他信息:
我的本地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。