title: Java maintaining a persistent TCP connection
body: <p>I am trying to send multiple data from server to client using TCP. I want to create only one TCP connection for the entire session. How do I go about doing this? </p>
  
  <p>I tried a code with the following flow, but the program stops after the first response is received.</p>
  
  <p>Client side</p>
  
  <pre><code>1.create sockets and streams
  2.send request for first data
  3.wait for response from server
  4.send next request &lt;----------- server doesn't seem to handle this request
  5.get next response from server
  </code></pre>
  
  <p>Server side</p>
  
  <pre><code>1.Create server socket and wait for incoming connections
  2.Parse incoming request
  3.Send response
  4.Parse next request
  5.Send next response
  </code></pre>
  
  <p>I do not close the sockets and streams on both sides while the session is alive.</p>
  
  <p><strong>Update</strong>
  Here is my code snippet:
  Client</p>
  
  <pre><code>public void processRequest() throws Exception {
  
      Socket tempSocket = new Socket("0.0.0.0", 6782);
  
      String requestLine = "This is request message 1" + CRLF;
  
      DataOutputStream outToServer = new DataOutputStream(tempSocket.getOutputStream());            
      BufferedReader inFromServer = new BufferedReader(new InputStreamReader(tempSocket.getInputStream())); 
  
      outToServer.writeBytes(requestLine + CRLF);
  
      String serverResponse = inFromServer.readLine();
      System.out.println(serverResponse);
  
      requestLine = "This is request message 2" + CRLF;
  
      outToServer.writeBytes(requestLine + CRLF);
  
      serverResponse = inFromServer.readLine();
      System.out.println(serverResponse);
  
      outToServer.close();
      inFromServer.close();
      tempSocket.close();
  }
  </code></pre>
  
  <p>Server</p>
  
  <pre><code>public void processRequest() throws Exception {
  
      createConnections();
  
      String requestLine = inFromClient.readLine();
      System.out.println(requestLine);
  
      String responseLine = "This is the response to messsage 1";
      outToClient.writeBytes(responseLine + CRLF);
  
      requestLine = inFromClient.readLine();
      System.out.println(requestLine);
  
      responseLine = "This is the response to message 2";
      outToClient.writeBytes(responseLine + CRLF);
  }
  </code></pre>
  
  <p>Output</p>
  
  <p>Client: </p>
  
  <pre><code>This is the response to messsage 1
  This is the response to message 2
  BUILD SUCCESSFUL (total time: 1 second)
  </code></pre>
  
  <p>Server:</p>
  
  <pre><code>This is request message 1
  
  null
  java.net.SocketException: Broken pipe
  </code></pre>