我有一个在Docker容器中运行的网络应用程序。该应用程序侦听我已转发给主机的端口1234。我的Mac(主机)上有一个简单的TCP客户端。客户端连接,发送一些字节,然后我看到套接字关闭异常。
在我的容器中运行的应用程序不会启动任何连接关闭。我认为连接丢失在中间的某个地方。是否有一些配置可以实现我的客户端和服务器之间的可靠连接。
我希望能够在我的应用程序和流程数据中模拟一个空闲会话。由于连接突然关闭,我无法做到。
下面是我的TCP客户端的代码。如果您注意到,我会在例外情况下重新连接。
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Responder implements Runnable {
private static Logger LOGGER = LoggerFactory.getLogger(Responder.class);
private Socket clientSocket;
private OutputStream outputStream;
private boolean isTestsDone = false;
@Override
public void run() {
if (isServerAvailable()) {
int tries = 10;
int counter = 0;
while (!isTestsDone) {
try {
outputStream = clientSocket.getOutputStream();
LOGGER.debug("Responder sending bytes");
outputStream.write(SampleMessageFactory.PACKET_HEADER);
outputStream.write(SampleMessageFactory.PACKET_MESSAGE_BODY);
LOGGER.info("counter is {}", counter);
counter++;
if (counter > tries) {
LOGGER.info("Number of Tries exceeded");
break;
}
Thread.sleep(12000);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
isServerAvailable();
}
}
}
}
public boolean isServerAvailable() {
boolean result = false;
for (;;) {
int port = 1234;
try {
URI uri = new URI(System.getProperty("docker.host"));
String dockerHost = uri.getHost();
LOGGER.debug("dockerHost is {}", dockerHost);
clientSocket = new Socket(dockerHost, port);
result = true;
break;
} catch (IOException e) {
LOGGER.error("The Server is not accepting connections on port " + port, e);
} catch (URISyntaxException e) {
LOGGER.error("Incorrect URI syntax ", e);
}
}
return result;
}
public boolean isTestsDone() {
return isTestsDone;
}
public void setTestsDone(boolean isTestsDone) {
this.isTestsDone = isTestsDone;
}
public void stop() {
try {
outputStream.close();
clientSocket.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}