bzak
bzak

Reputation: 495

Java can not connect to Server Socket

I have a multi threaded Server Socket running on 1 computer running as follows:

static void createServer() throws IOException {
    //use this ip for other user
    System.out.println(InetAddress.getLocalHost());
    // establish server socket
    try {
        ServerSocket s = new ServerSocket(8888);

        while (true) {
            Socket incoming = s.accept();
            Runnable r = new ThreadedEchoHandler(incoming, map);
            Thread t = new Thread(r);
            t.start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Then from another computer I try to connect to the Server(using the ip from first computer 192.168.162.1) as follows:

public void registerCmnd(Scanner keys) throws IOException {
    InetAddress ip = InetAddress.getByName("first computer ip");
    try (Socket s = new Socket(ip, 8888)) {
        .....
        .....
   }

}

I am getting a java.net.ConnectException.

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at User.registerCmnd(User.java:45)
at User.main(User.java:28)

Any ideas?

Upvotes: 0

Views: 3026

Answers (2)

Stephen C
Stephen C

Reputation: 718678

It doesn't look like the problem is in the code itself.

There are a number of possible causes for this, including

  • A firewall, on the client, the server, a hypervisor stack, or the network is blocking access.

  • You are using the wrong IP address for the server on the client

  • You are using the wrong server port number on the client (not in this case)

  • You are using an IP address that isn't routed from the client to the server. For example, if the server's IP is a private address, and the client is on a different network.

  • Someone has misconfigured the packet forwarding (e.g. iptables) or routing (e.g. routed, etc) on the client or server. Or somewhere else.


If I were you, I would see whether one computer can PING the other and vice-versa. If that fails, then check the routing tables. Note that this is most likely a network configuration problem, not a programming problem.

Upvotes: 1

joe pelletier
joe pelletier

Reputation: 399

You either have the wrong ip, the port is not forwarded, or both. also make sure to run the server first.

Upvotes: 0

Related Questions