Search code examples
javasocketsdistributed-computing

Is it good approach to make connection per message while designing distributed system over socket based network?


I am designing a distributed system by creating network using sockets in java. It has different threads which are communicating simultaneously with other servers. While designing distributed system or any network application which involves simultaneous connections is it good to create connections once and then communicating using io-streams or connections should be made and closed per message?


Solution

  • i dont think its a good idea to make a connection each time in when client wants to send a message because you have to wait untill server accept your connection.

         //Server side code.
        ServerSocket listener = new ServerSocket(9090);
        Socket socket = listener.accept();
        //client code
        Socket s = new Socket(serverAddress, 9090);
    

    you can create a single conection and use inputStreamReader in the rest of code to listen input and output from the both sides, that approach will make your app faster than creating a connection each time.

    //client code
     BufferedReader input =new BufferedReader(new InputStreamReader(s.getInputStream()));
    
    //serverCode
    PrintWriter out =new PrintWriter(socket.getOutputStream(), true);