我是客户端 - 服务器连接。客户端以预定义的格式向服务器发送请求以在服务器处启动某些处理。服务器执行此处理,然后以预定义的格式将结果返回给客户端。
服务器处理最多可能需要15分钟。
我使用reqObject.toString()将请求/响应转换为字符串,然后使用readUTF和writeUTF通过网络发送(读取整个缓冲区)。
现在问题:
代码段: 客户:
Socket server = null;
OutputStream outToServer = null;
DataOutputStream out = null;
InputStream inFromServer = null;
DataInputStream in = null;
if(msg != null){
try
{
server = new Socket(serverIp, serverPort);
server.setSoTimeout(1000 * 60 * timeoutInMins); //set to 30 mins
outToServer = server.getOutputStream();
out = new DataOutputStream(outToServer);
out.writeUTF(msg);
out.flush();
// now wait for Server reply
inFromServer = server.getInputStream();
in = new DataInputStream(inFromServer);
responseString = in.readUTF();
// do something with response
}
服务器:
ServerSocket serverSocket = null;
Socket client = null;
try{
serverSocket = new ServerSocket(port);
} catch (Exception e) {//log this}
try
{
while(true)
{
client = serverSocket.accept();
if(client.getRemoteSocketAddress() != null){
try{
ReqObject request = getRequest(client);
// do processing. this may take upto 10-15 mins at max
sendBackResponse(client, request);
}
// do remaining
private void sendBackResponse(Socket client, ReqObject result) throws IOException {
DataOutputStream out = null;
try{
out = new DataOutputStream(client.getOutputStream());
String outToClient = result.toString();
out.writeUTF(outToClient);
out.flush();
} finally {
try{out.close();}catch(IOException e){}
}
}
private ReqObject getRequest(Socket client) throws IOException {
DataInputStream in = null;
in = new DataInputStream(client.getInputStream());
String incoming = in.readUTF();
return convertMessageToRequest(incoming);
}
答案 0 :(得分:0)
在5分钟不活动之后,连接被中间的防火墙断开/阻止。
为了解决这个问题,我开始每2分钟发送一次心跳消息(包含垃圾数据)。这使得连接保持活动直到操作完成。
注意:java提供的keepalive()方法没有帮助..