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
發佈相關代碼片段 - 很難對隱形代碼提出建議。 :) – sarnold 2012-03-02 03:30:36
你寫了雙方,當然你可以附加一個調試器到服務器,並觀察第二個請求到達時會發生什麼? – 2012-03-02 04:17:53
已發佈必要的代碼片段和調試器輸出:) – shyamsundar2007 2012-03-02 16:54:49