简体   繁体   中英

Java socket program for client and server communication auto reconnect

I want to develop client and server communication and I have written some code for client and server but once the client and server connect, there's no need to reconnect again and again. However, in my current code they keep re-connecting again and again.

  1. InetAddress host = InetAddress.getLocalHost();
  2. Socket s = new Socket(host.getHostName(), 4321);

The second line will create new connection each time and this is the problem I'm trying to solve (they only need to connect once).

ClientClass.java

public class CientClass {

public static void main(String[] args)  
  {
    System.out.println("CLIENT SITE");
    while (true) {
        try {
            InetAddress host = InetAddress.getLocalHost();
            Socket s = new Socket(host.getHostName(), 4321);
            DataOutputStream dout = new DataOutputStream(s.getOutputStream());
            Scanner sc = new Scanner(System.in);
            System.out.println("Ener for server:");
            String data = sc.next();
            dout.writeUTF(data);
        }
        catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
  }
}

Serverclass.java

public class Serverclass {

public static void main(String[] args) {
    System.out.println("SERVER SITE");
    while (true) {
        try {
            ServerSocket ss = new ServerSocket(4321);
            Socket s = ss.accept();
            DataInputStream din = new DataInputStream(s.getInputStream());
            String str = (String) din.readUTF();
            System.out.println("message:" + str);
            ss.close();
        }
        catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
  }
}

The clientClass reads commands from the console and sends to the server but it should not keep reconnecting after the initial connection.

And in a situation like restart the server and the client should connect automatically and and client should be able to send the commands to the server.

I think I don't need to change the serverclass code. Only need to change the clientClass code. How?

Okay so there are two main reasons why there will always be established a new connection.

First of all for every cycle of your while(true) loop in your ServerClass you're creatinga new server socket and await a new connection by calling ServerSocket.accept() which is also a blocking operation, which means the server keeps blocking until a new connection arrives.

The second reason for this behaviour is, that you are always enforcing a new connection from your ClientClass by creating a new socket. Sockets establish end-to-end-connections. Once created and conencted you don't have to make another one.

The most convientient fix for you would be to replace the while(true) loop so that it only covers the real send/receive logic in some way like this:

ClientClass

  try
  {
    InetAddress host = InetAddress.getLocalHost();
    Socket s = new Socket( host.getHostName(), 4321 );
    DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
    while ( isAlive )
    {
      Scanner sc = new Scanner( System.in );
      System.out.println( "Ener for server:" );
      String data = sc.next();
      dout.writeUTF( data );
    }
  }
  catch ( Exception e )
  {
    System.out.println( e );
    e.printStackTrace();
  }

ServerClass

try
      {
        ServerSocket ss = new ServerSocket( 4321 );
        Socket s = ss.accept();
        DataInputStream din = new DataInputStream( s.getInputStream() );
        while ( isAlive )
        {
          String str = (String) din.readUTF();
          System.out.println( "message:" + str );
        }
        ss.close();
      }
      catch ( Exception e )
      {
        System.out.println( e );
        e.printStackTrace();
      }

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