简体   繁体   中英

Java Socket connecting to a public ip-address

I need to make a server and client that connects to the server.

Problem : "the server works. the client can only connect to localhost, it cannot connect to a server on the internet. I want the client to connect to the server, via a public ip-address that the server is hosted on."

First of all, I have made sure that the port is forwarded and reachable i have tested the port, secondly i have disabled firewall completely from the server machine.

below is the test code i am using:

The Server: nothing fancy just simple - terminates if a client is connected, else just awaits a connection.

public class Server {
public static void main(String args[]) {
    try {
        ServerSocket srvr = new ServerSocket(52000);
        srvr.accept();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
  }
} 

The Client: I have used no-ip.com to mask the ip of the server to "biogenserver2.noip.me". Using .getCanonicalHostName(); will return the ip.

public class Client {
public static void main(String args[]) {
    try {
        String ip = Inet4Address.getByName("somets.noip.com").getCanonicalHostName();
        InetSocketAddress sa = new InetSocketAddress(ip, 52000);
        //Socket skt = new Socket("0.0.0.0", 52000); //local - this works fine.
        Socket skt = new Socket();
        skt.connect(sa);
    }
    catch(Exception e) {
        e.printStackTrace();
    }
  }
}

When i run this the server connects fine, but the client returns a "connection timeout" exception

Any help will be appreciated. Thanks.

Answer:

"Just for clarity: You have checked the port is open via public IP as returned by no-ip and the server will quit without exception when you run that little testclient (on a machine that is not the server machine) - is that correct?" Fildor

TL:DR

Don't run the client and server on the same machine and the same network trying to connect to your server through your public ip then to your own local network will result in a client timeout exception

I was running the client and server on the same machine and also the same network. This caused the client timeout exception. I tried running the Client on a different machine and a different network and i was able to connect successfully.

What version of IP protocol your application uses? On linux, you may figure it out with netstat -tunap | grep 52000 netstat -tunap | grep 52000 and watching whether first field is tcp or tcp6 . If latter, then it is possible that problem with IPv6 connectivity exists and you may want to prefer using IPv4 to IPv6 by specifying -Djava.net.preferIPv4Stack=true to JVM.

在服务器接受客户端之前,3次握手完成并且客户端超时可能需要一些时间

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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