java 持久连接,Java维护持久的TCP连接

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

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

}

Server

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

}

Output

Client:

This is the response to messsage 1

This is the response to message 2

BUILD SUCCESSFUL (total time: 1 second)

Server:

This is request message 1

null

java.net.SocketException: Broken pipe

解决方案

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

String requestLine = "This is request message 1" + CRLF;

.....

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值