2012-03-02 155 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