简体   繁体   中英

Java Networking “Connection Refused: Connect”

I have been trying to get a simple networking test program to run with no results.

Server:

import java.io.*;
import java.net.*;

public class ServerTest {
    public static void main(String[] args) {
    final int PORT_NUMBER = 44827;

    while(true) {
        try {
        //Listen on port
        ServerSocket serverSock = new ServerSocket(PORT_NUMBER);
        System.out.println("Listening...");

        //Get connection
        Socket clientSock = serverSock.accept();
        System.out.println("Connected client");

        //Get input
        BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
        System.out.println(br.readLine());

        br.close();
        serverSock.close();
        clientSock.close();
        } catch(Exception e) {
        e.printStackTrace();
        }
    }
    }
}

Client:

import java.io.*;
import java.net.*;

public class ClientTest {
    public static void main(String[] args) throws IOException {
    final int PORT_NUMBER = 44827;
    final String HOSTNAME = "xx.xx.xx.xx";

    //Attempt to connect
    try {
        Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
            PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
        //Output
        out.println("Test");
        out.flush();

        out.close();
        sock.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
    }
}

The program works just fine when I use 127.0.0.1 or my internal IP for the hostname. But whenever I switch to my external IP address, it throws a java.net.ConnectException: Connection refused: connect error.

I purposely picked such an uncommon port to see if that was the problem, with no luck. I can connect with no problems using telnet, but when I try to access the port with canyouseeme.org, it tells me the connection timed out. I even tried to disable all firewalls and antivirus including the Windows default ones and the router firewall, with all ports forwarded and DMZ enabled, and it still says that the connection timed out. I use Comcast as my ISP, and I doubt that they block such a random port.

When I use a packet tracer, it shows TCP traffic with my computer sending SYN and receiving RST/ACK, so it looks like a standard blocked port, and no other suspicious packet traffic was going on.

I have no idea what is going on at this point; I have pretty much tried every trick I know. If anyone know why the port might be blocked, or at least some way to make the program work, it would be very helpful.

These problem comes under the following situations:

  1. Client and Server, either or both of them are not in network.

  2. Server is not running.

  3. Server is running but not listening on port, client is trying to connect.

  4. Firewall is not permitted for host-port combination.

  5. Host Port combination is incorrect.

  6. Incorrect protocol in Connecting String.

How to solve the problem:

  1. First you ping destination server. If that is pinging properly, then the client and server are both in network.

  2. Try connected to server host and port using telnet. If you are able to connect with it, then you're making some mistakes in the client code.

For what it's worth, your code works fine on my system.

I hate to say it, but it sounds like a firewall issue (which I know you've already triple-checked) or a Comcast issue , which is more possible than you might think. I'd test your ISP .

I had the same problem because sometimes the client started before server and, when he tried to set up the connection, it couldn't find a running server.

My first (not so elegant) solution was to stop the client for a while using the sleep method:

try {
   Thread.sleep(1000);
} 
catch (InterruptedException e) {
   e.printStackTrace();
}

I use this code just before the client connection, in your example, just before Socket sock = new Socket(HOSTNAME, PORT_NUMBER);

My second solution was based on this answer. Basically I created a method in the client class, this method tries to connect to the server and, if the connection fails, it waits two seconds before retry. This is my method:

private Socket createClientSocket(String clientName, int port){

    boolean scanning = true;
    Socket socket = null;
    int numberOfTry = 0;

    while (scanning && numberOfTry < 10){
        numberOfTry++;
        try {
            socket = new Socket(clientName, port);
            scanning = false;
        } catch (IOException e) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }

    }
    return socket;
}

As you can see this method tries to create a socket for ten times, then returns a null value for socket, so be carefull and check the result.

Your code should become:

Socket sock = createClientSocket(HOSTNAME, PORT_NUMBER);
if(null == sock){ //log error... }

This solution helped me, I hope it helps you as well. ;-)

Likely the server socket is only being bound to the localhost address. You can bind it to a specific IP address using the 3-argument form of the constructor.

I assume you are using a Router to connect to Internet. You should do Port Forwarding to let public access your internal network. Have a look at How do you get Java sockets working with public IPs?

I have also written a blog post about Port forwarding, you might wanna have a look :) http://happycoders.wordpress.com/2010/10/03/how-to-setup-a-web-server-by-yourself/

But I still couldn't get this accessed over public IP, working on it now...

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