我有一个运行在 Tomcat 6 上的 Web 应用程序,安装在 Windows Server 2003 上。此应用程序打开与不同服务器的套接字连接以检索一些数据。这个应用程序已经工作了几个月。但是由于某种原因,Web 应用程序有两次停止工作。在这两种情况下,运行 netstat 命令(使用 -ano)在 Web 应用程序通过套接字连接连接的端口上显示了大约 4.000 个 tcp 连接(处于 TIME_WAIT 状态)。
奇怪的事情从这里开始:我停止了tomcat,过了一会儿那些连接断开了(再次运行netstat)。我重新启动tomcat,这些连接都回到TIME_WAIT状态!!!
我不知道为什么要重新打开这些连接。我错过了一些非常明显的东西。有任何想法吗?
谢谢你。
编辑:
这是进行套接字管理的代码:
public void openSocketConnection() throws Exception {
socket = createSingleSocket();
socket.setSoTimeout(5000);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
}
/**
* Closes socket and output input streams.
*/
public void closeSocketConnection() throws IOException {
socket.close();
out.close();
in.close();
}
/**
* Writes the input to the socket and returns the output response
*
* @param input
* a String to write on the socket
* @return output a String that the socket returns
* @throws Exception
*/
public String writeReadSocket(String input) throws Exception {
openSocketConnection();
out.println(input);
logger.debug("Socket Input:" + input);
String output = in.readLine();
logger.debug("Socket output:" + output);
closeSocketConnection();
return output;
}
/**
* Method overiden by Spring. We use the method injection technique, so that we have a new socket instance in every call to openSocketConnection()
* method
*/
public abstract Socket createSingleSocket();
调用的方法是 writeReadSocket。
spring 使用了最后一个方法(createSingleSocket),因此我可以为每次调用 openConnection() 方法创建一个新的 Socket 实例(顺便说一下,我不确定为每个请求创建一个新的 Socket 是否正确)。在 Spring 配置文件中,我有这个:
<!-- prototype scope is used to instantiate a new socket instance in every createSingleSocket() method call. -->
<bean id="socket" class="java.net.Socket" scope="prototype">
<constructor-arg type="String" value="${socket.url}"/>
<constructor-arg type="int" value="${socket.port}"/>
</bean>
<bean id="socketConnector" class="gr.diassa.dsjsonrpcsuite.socket.SocketConnector">
<lookup-method name="createSingleSocket" bean="socket"/>
</bean>