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