Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi
I am doing one socket programming in java. If server socket is down for a while then start again after that can get auto connection with the client which the server connect with previously.If possible can any one help me how to do it?

What I have tried:

This are my code. Can help me to handle this?
package multiclients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger; 

public class STServer {
    
        // Declaring the asynchronous thread class
        public static class QueueClientThread extends Thread {
        private BufferedReader m_in;
        private PrintWriter m_out;
        // Passing buffered reader and print writer objects to the constructor
        public QueueClientThread(BufferedReader in, PrintWriter out) {
            m_in = in; m_out = out;
        }
        public void run() {
            // Entering the endless eternal loop to make sure that the asynchronous
            // threads is proceeding to receive incoming messages in real-time mode
            while (true) {
                try {
                    String msg_buf = "Thank You";
                    // Fetching data from socket by invoking buffered reader's
                    // readLine(…) method.
                    while ((msg_buf = m_in.readLine()) != null) {
                        // Printing diagnostic message
                        System.out.println("Response from singlethreaded server: " + msg_buf);
                        // Sending out the modified data back to client
                        m_out.println("Response from singlethreaded server: " + msg_buf+ " Thank You");
                    }
                // Catch the IO socket exception
                } 
                    catch (IOException ex) {
                    // Log the exception
                    Logger.getLogger(STServer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }    
    
    public static void main(String[] args) throws IOException {
        Integer.parseInt("5058");
             
        // Instantinate server socket object to listen tcp port 5058
        @SuppressWarnings("resource")
		ServerSocket serverSocket = new ServerSocket(Integer.parseInt("5058"));     
        // Entering endless eternal loop to enforce the single threaded server
        // receive incoming messages forwarded from clients by the multi-threaded 
        // server and respond each incoming message back to multi-threaded server
        while (true) {
            try {
                    // Getting client socket object
                    Socket clientSocket = serverSocket.accept();
                    // Instantiate print writer to send data back to clients by using output stream 
                    PrintWriter out =
                       new PrintWriter(clientSocket.getOutputStream(), true);                 

                    new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()));

                    // Run the asynchronous thread to receive incoming requests
                    new QueueClientThread(new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream())), out).start();
            
                // Catch IO exception in case if socket operations fail
                } catch (IOException ex) {
                    Logger.getLogger(STServer.class.getName()).log(Level.SEVERE, null, ex);
                }       
        }
    }}

Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MTServer {

    public static class QueueClientThread extends Thread {
        private BufferedReader m_in;
        private PrintWriter m_out;
        public QueueClientThread(BufferedReader in, PrintWriter out) {
            m_in = in; m_out = out;
        }
        public void run() {
            while (true) {
                try {
                    String msg_buf = "\0";
                    while ((msg_buf = m_in.readLine()) != null) {
                        System.out.println("Message sent back to client: " + msg_buf);
                        m_out.println("Message sent back to client: " + msg_buf);
                    }
                }catch (InterruptedIOException iioe)
                {
             	   System.err.println ("Remote host timed out");
             	} catch (IOException ex) {
                    Logger.getLogger(MTServer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }    
    
    public static class QueueMTServerThread extends Thread {
        private Socket m_Socket;
        public QueueMTServerThread(Socket socket) {
            m_Socket = socket;
        }
        @SuppressWarnings("resource")
		public void run() {
            try (
                PrintWriter out =
                    new PrintWriter(m_Socket.getOutputStream(), true);                   
                BufferedReader in = new BufferedReader(
                    new InputStreamReader(m_Socket.getInputStream()));
            ) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println(inputLine);
                    
                    String hostName = "127.0.0.1";
                    int portNumber = Integer.parseInt("5058");
            
                    Socket clientSocket = new Socket(hostName, portNumber);
                    PrintWriter outputStream = new PrintWriter(
                            clientSocket.getOutputStream(), true);

                    outputStream.println(inputLine);
                    
                    new QueueClientThread(new BufferedReader(
                      new InputStreamReader(clientSocket.getInputStream())), out).start();
                }
            } catch (InterruptedIOException iioe)
            {
         	   System.err.println ("Remote host timed out");
         	}catch (IOException e) {
                System.out.println(e.getMessage());
            }            
        }   
    }
    
    @SuppressWarnings({ "resource", "unused" })
	public static void main(String[] args) throws IOException {
        int portNumber = Integer.parseInt("5056");
        try {
            ServerSocket serverSocket = new ServerSocket(
                    Integer.parseInt("5056"));     

            while (true) {
                Socket clientSocket = serverSocket.accept();
                new QueueMTServerThread(clientSocket).start();
            }
            
        }catch (InterruptedIOException iioe)
        {
     	   System.err.println ("Remote host timed out");
     	} catch (IOException ex) {
            Logger.getLogger(MTServer.class.getName()).log(Level.SEVERE, null, ex);
        } 
			
    }


	
	
}
Posted
Updated 8-Aug-18 16:54pm
v3
Comments
ZurdoDev 8-Aug-18 8:14am    
I don't know Java but I would think one way would be to have the client periodically query to see if the server is available. Once it is available, then your connection is established again.
Mohibur Rashid 8-Aug-18 22:27pm    
It is the answer.
FerdouZ 8-Aug-18 22:37pm    
Hi Rashid,
Can you share the code?
Mohibur Rashid 9-Aug-18 0:03am    
no!

1 solution

You can have a separate thread check the socket every x seconds:

1) Check LAST status of socket
2) If not OK or closed, then (re)connect

The "worker" thread(s) simply "send" only when the socket's "status" is OK / available; else they "return" (until the "connection worker" succeeds).

Simplifies the "client" calls.
 
Share this answer
 
Comments
FerdouZ 8-Aug-18 22:55pm    
Hi Gerry,
Actually I am confused about this because I am a beginner. I share my code above can you check for me?
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900