简体   繁体   English

Java-TCP套接字仅在LAN中连接

[英]Java - TCP socket only connects in LAN

I have created a small TCP server but it only connects to other computers on my LAN. 我创建了一个小型TCP服务器,但它仅连接到LAN上的其他计算机。 I did forward the port but it is still not working. 我确实转发了该端口,但仍无法正常工作。

connection method: 连接方式:

    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;
}

listen method: 监听方法:

    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();
    }
}

opening the server: 打开服务器:

    private void initializeServer(){
    try{
        serverSocket = new ServerSocket(port,8,InetAddress.getByName(ip));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

It appears as if you're supplying an IP address to InetAddress.getByName() . 看起来好像你提供一个IP地址InetAddress.getByName() It requires a host name. 它需要一个主机名。 Specifically, it needs the host name corresponding to the network that the port is forwarded to. 具体来说,它需要与端口转发到的网络相对应的主机名。 For example, if you're forwarding to your computer's (internal) ip address (say, 192.168.1.10 ), then it needs the host name that corresponds to that address (for example mycomputer.local ). 例如,如果要转发到计算机的(内部)IP地址(例如192.168.1.10 ),则它需要与该地址相对应的主机名(例如mycomputer.local )。 Java needs that host name to know what interface it should listen on. Java需要该主机名来知道它应该侦听的接口。 I'm surprised it worked at all. 我很惊讶它真的奏效了。

If you do want to supply the IP address and not the host name, use InetAddress.getByAddress(byte[] addr) instead: 如果确实要提供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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM