我创建了一个小型TCP服务器,但它只连接到局域网上的其他计算机。我确实转发了端口,但仍然没有工作。
连接方法:
private boolean connect(){
try {
socket = new Socket(InetAddress.getByName(ip), port);
System.out.println("socket created");
dataOutput = new DataOutputStream(socket.getOutputStream());
dataInput = new DataInputStream(socket.getInputStream());
accepted = true;
} catch (IOException e) {
System.out.println("Unable to connect to the server");
return false;
}
System.out.println("Successfully connected to the server.");
return true;
}
听法:
private void listenForServerRequest(){
Socket socket = null;
try{
socket = serverSocket.accept();
dataOutput = new DataOutputStream(socket.getOutputStream());
dataInput = new DataInputStream(socket.getInputStream());
accepted = true;
System.out.println("client joined");
}catch(IOException e){
e.printStackTrace();
}
}
打开服务器:
private void initializeServer(){
try{
serverSocket = new ServerSocket(port,8,InetAddress.getByName(ip));
}
catch(Exception e){
e.printStackTrace();
}
}
答案 0 :(得分:1)
显示,就像您向InetAddress.getByName()
提供IP地址一样。它需要一个主机名。具体来说,它需要与端口转发到的网络对应的主机名。例如,如果您转发到计算机的(内部)IP地址(例如,192.168.1.10
),那么它需要与该地址对应的主机名(例如mycomputer.local
)。 Java需要该主机名来知道它应该监听哪个接口。我很惊讶它有用。
如果您确实想提供IP地址而不是主机名,请改用InetAddress.getByAddress(byte[] addr)
:
byte[] addr = new byte[4];
addr[0] = 192;
addr[1] = 168;
addr[2] = 1;
addr[3] = 10;
...
serverSocket = new ServerSocket(port,8,InetAddress.getByAddress(addr));