Take the 2-minute tour ×

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?

I tried a code with the following flow, but the program stops after the first response is received.

Client side

1.create sockets and streams
2.send request for first data
3.wait for response from server
4.send next request <----------- server doesn't seem to handle this request
5.get next response from server

Server side

1.Create server socket and wait for incoming connections
2.Parse incoming request
3.Send response
4.Parse next request
5.Send next response

I do not close the sockets and streams on both sides while the session is alive.

Update Here is my code snippet: Client

public void processRequest() throws Exception {

    Socket tempSocket = new Socket("", 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();

    requestLine = "This is request message 2" + CRLF;

    outToServer.writeBytes(requestLine + CRLF);

    serverResponse = inFromServer.readLine();



public void processRequest() throws Exception {


    String requestLine = inFromClient.readLine();

    String responseLine = "This is the response to messsage 1";
    outToClient.writeBytes(responseLine + CRLF);

    requestLine = inFromClient.readLine();

    responseLine = "This is the response to message 2";
    outToClient.writeBytes(responseLine + CRLF);



This is the response to messsage 1
This is the response to message 2
BUILD SUCCESSFUL (total time: 1 second)


This is request message 1

java.net.SocketException: Broken pipe
share|improve this question
Post the relevant code snippets -- it's hard to make suggestions on invisible code. :) –  sarnold Mar 2 '12 at 3:30
You wrote both sides, surely you can attach a debugger to the server and watch what happens when the second request arrives? –  Jim Garrison Mar 2 '12 at 4:17
Have posted the necessary code snippets and the debugger output :) –  shyamsundar2007 Mar 2 '12 at 16:54
add comment

1 Answer

up vote 1 down vote accepted

I think the problem is in your client code. You wrote:

    outToServer.writeBytes(requestLine + CRLF);

You add CRLF to requestLine, and add it again when send it to server. Ensure that adding CRLF only once per message you want to send, it will behave as you want.

share|improve this answer
Thanks a lot! that was indeed the problem with my code -.- Took me a couple of hours of debugging to find it out! –  shyamsundar2007 Jul 1 '12 at 16:38
add comment

Your Answer


