How do I reconnect a client when server is down in Java?

这一生的挚爱 提交于 2019-12-12 02:36:39

问题


I have a server that accepts sockets from whenever a client connects. I want to be able to shutdown my local server and let my client try to reconnect for about 5 times, and if I start my server the client should indicate that you have reconnected again.

I understand somewhat that this is done in the try{} catch(IOException){Here goes the code for handleing reconnect} I want to use the same socket that I first used to connect. I don't want to create a new Client cause then I have to enter username and stuff like that all over again

I tried to creating a new socket like clientSocket = new Socket("localhost", portnr) but I don't know if this is the correct way to go. If you have examples that answers this please link them. I dont mind reading as long as it is good documented. Thanks in advance!

EDIT. Here is my Client Class

public class Client {       

public static void main(String[] args) {        
    Client client = new Client();
    client.connect();
}
//------------------------------------------------------------

//METHOD CONNECT
//------------------------------------------------------------    
private void connect(){
    int reConnectTries = 0;
    Socket clientsocket;
    try {
        //------------------------------------------------
        //Sets up variables needded for execution            
        clientsocket = new Socket("localhost", 8900);
        DataOutputStream OUT = new DataOutputStream(clientsocket.getOutputStream());            
        ListenforMessages listen = new ListenforMessages(clientsocket);
        //We don't want to enter username all the time
        //So this goes not in the while-loop
        //------------------------------------------------
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter username");
        String username = keyboard.nextLine();
        //Sends username to sever so it can be added to a list
        OUT.writeUTF(username);
        //------------------------------------------------

        //------------------------------
        //Creates a thread to listen on messages from server(Other clients in this case)
        Thread trd = new Thread(listen);
        trd.start();
        //------------------------------            
        while (true) {   

            try {
                String sendMessage = keyboard.nextLine();
                OUT.writeUTF(sendMessage);                    
                OUT.flush();
            } catch (Exception e) {
                System.err.println("Could not send message to server. " + e);
            }
        }           
    } catch (IOException e) {
        System.err.println("Couldnt establish a connection: " + e);
    }        
}
//------------------------------------------------------------    

//CLASS FOR HANDLEING INPUT. We create a class for input on a new thread
//This is cause we don't want it to block other processes.
//----------------------------------------------------------------    
class ListenforMessages implements Runnable{

    Socket mySocket;
    DataInputStream IN;
    public ListenforMessages(Socket X) throws IOException {
        this.mySocket = X;
    }

    @Override
    public void run() {
        try {
            IN = new DataInputStream(mySocket.getInputStream());
            while (true) {                    
                System.out.println(IN.readUTF());   
            }
        } catch (Exception e) {
            System.err.println("Couldn't fetch message from server.Error: " + e);                
        }            
    }

}
}

回答1:


There's a couple of solutions to this problem, but a simple one would to be have the client try to reconnect (open a new connection to the server) at set intervals. For example, you could try something like this to have your client try to reconnect once every 3 minutes:

while(true) {
    try {
        clientSocket = new Socket("localhost", portnr);
        break; // We connected! Exit the loop.
    } catch(IOException e) {
        // Reconnect failed, wait.
        try {
            TimeUnit.MINUTES.sleep(3);
        } catch(InterruptedException ie) {
            // Interrupted.
        }
    }
}

This way, the client will try to connect, and if it fails, wait for 3 minutes before trying again.




回答2:


import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.NoRouteToHostException;
import java.net.SocketAddress;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.net.ConnectException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

final class TCPClient{

    private static Scanner in ;
    private static DataOutputStream douts;
    private static OutputStream outs;
    private static InputStream ins;
    private static DataInputStream dins;
    private static String ip;
    private static Integer port;
    private int count = 0;
    private static int times;

    public TCPClient(){
        serverConTest(port);
    }

    private boolean portIsOpenOrNot(String ip, int port){
        try{
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(ip,port),500);
            socket.close();
            return true;
        }catch(Exception e){
        }

        return false;
    }

    private void serverConTest(int port){

                while(true){
                    try{
                        InetAddress addr = InetAddress.getByName(ip);
                        SocketAddress sockaddr = new InetSocketAddress(addr,port);
                        Socket socket = new Socket();
                        System.out.println("Connecting To server...");
                        socket.connect(sockaddr);

                        Thread.sleep(1000);
                        boolean isactive = true;
                        if(portIsOpenOrNot(ip,port)){
                            outs = socket.getOutputStream();
                            douts = new DataOutputStream(outs);
                            System.out.println("Sending Request to server:");
                                while(isactive){
                                    Thread.sleep(1000);

                                    douts.writeUTF("Are you Alive..!");
                                    ins = socket.getInputStream();
                                    dins = new DataInputStream(ins);
                                    System.out.println("Response from server : "+dins.readUTF());
                                }
                        }

                    }catch(SocketException e){
                        System.out.println("Connection lost");
                    }catch(IOException e){
                        break;
                    }catch(InterruptedException e){
                        System.out.print("connection timeout in 50 second.");
                        break;
                    }
                }
    }

    public static void main(String[] args){
        in = new Scanner(System.in);
        System.out.print("Enter ip : ");
        ip = in.nextLine();
        System.out.print("Enter Port : ");
        port = Integer.parseInt(in.next());
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future future = executorService.submit(new Runnable() {
            public void run() {
                new TCPClient();
            }
        });

        try{
            future.get(50, TimeUnit.SECONDS);
        }catch(InterruptedException e){

        }catch(ExecutionException e){

        }catch(TimeoutException e){
            executorService.shutdownNow();
        }
    }
}

This sample will give you the complete understanding that when the server restarts then client will reconnects.




回答3:


I didnt read all your code but this one is working for me

And dont forget to add the Server class and the method send that sends messages...

Client :

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client {
static Socket sock=null;
static DataInputStream in=null;
static DataOutputStream out=null;
static boolean connected=false;

static String currentip="";
static int currentport=0;  

static void refreching(){

try {
    in=new DataInputStream(sock.getInputStream());
    out=new DataOutputStream(sock.getOutputStream());

    Thread gg=new Thread() {
        String msg="";
    public void run() {
        while(connected) {
        try {
            msg=in.readUTF();
            System.out.println(msg);

        } catch (IOException e) {
           connected=false;
           System.out.println("Reconnecing...");
           while(!connected)
           connect(currentip,currentport);
        }
      }

        }
    };
    gg.start();
}
catch(Exception e) {
    System.out.println("Problem while reading incoming and outgoing"+    
    "messages!");
    connected=false;

            }
}

static void connect(String iphost, int port){
try{
sock=new Socket(iphost,port);
currentip=iphost;
currentport=port;
connected=true;
refreching();
System.out.println("Connected!");
}
catch(Exception e){
System.out.println("Cant connect !");
connected=false;
  }
}

public static void main(String[] args) {
connect("127.0.0.1",1234); //Example you can enter another's computer ip 
                          //adress if connected to the same network !!!
//Send(Message_To_Server); Dont forget to add the sending code!!!
//Maybe i'll upload a video one day==>how to create a chat application
}


来源:https://stackoverflow.com/questions/29018269/how-do-i-reconnect-a-client-when-server-is-down-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!