2012-03-02 191 views
1

我想從服務器使用TCP發送多個數據到客戶端。我想爲整個會話創建一個TCP連接。我如何去做這件事?Java保持持續的TCP連接

我試着用下面的流程代碼,但程序收到第一個響應後停止。

客戶端

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 

服務器端

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

我不關閉套接字和同時會話存活兩側流。

更新 這裏是我的代碼片段: 客戶

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(); 
} 

服務器

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

輸出

客戶:

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 

null 
java.net.SocketException: Broken pipe 
+3

發佈相關代碼片段 - 很難對隱形代碼提出建議。 :) – sarnold 2012-03-02 03:30:36

+0

你寫了雙方,當然你可以附加一個調試器到服務器,並觀察第二個請求到達時會發生什麼? – 2012-03-02 04:17:53

+0

已發佈必要的代碼片段和調試器輸出:) – shyamsundar2007 2012-03-02 16:54:49

回答

2

我認爲這個問題是在客戶端代碼。您寫道:

String requestLine = "This is request message 1" + CRLF; 
    ..... 
    outToServer.writeBytes(requestLine + CRLF); 

您將CRLF添加到requestLine,並在將它發送到服務器時再次添加它。確保每個要發送的郵件只添加一次CRLF,它將按照您的要求運行。

+0

非常感謝!這確實是我的代碼的問題 - 。 - 花了我幾個小時的調試來找出它! – shyamsundar2007 2012-07-01 16:38:38