Java Networking “Connection Refused: Connect”

后端 未结 5 2167
你的背包
你的背包 2020-12-16 19:32

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 ServerT         


        
5条回答
  •  不知归路
    2020-12-16 20:05

    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. ;-)

提交回复
热议问题