繁体   English   中英

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

[英]Java - TCP socket only connects in LAN

我创建了一个小型TCP服务器,但它仅连接到LAN上的其他计算机。 我确实转发了该端口,但仍无法正常工作。

连接方式:

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

看起来好像你提供一个IP地址InetAddress.getByName() 它需要一个主机名。 具体来说,它需要与端口转发到的网络相对应的主机名。 例如,如果要转发到计算机的(内部)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));

暂无
暂无

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

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