在我的应用程序中,我创建了一个带有一些端口的ServerSocket实例。完成后,我关闭套接字,但当我尝试在同一端口上创建新的ServerSocket时,它抛出:
"java.net.BindException: Address already in use"如果我使用不同的端口创建ServerSocket,那么它就可以工作。
ServerSocket.isClosed也返回true
有什么问题吗?
public void run() {
try {
BufferedInputStream bufferedinputstream = new BufferedInputStream(
new FileInputStream(fileReq));
BufferedOutputStream outStream = new BufferedOutputStream(
cs.getOutputStream());
byte buffer[] = new byte[1024];
int read;
System.out.println(cs);
while ((read = bufferedinputstream.read(buffer)) != -1)
{
outStream.write(buffer, 0, read);
outStream.flush();
}
System.out.println("File transfered");
outStream.close();
bufferedinputstream.close();
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Exce....");
System.out.println(e.getMessage());
}
finally
{
if ( cs != null)
try {
int usedPort=cs.getLocalPort();
System.out.println("Closing "+cs);
cs.close();
System.out.println(cs+" Closed");
System.out.println("asd"+cs.isClosed());
portManager.getInstance().mp.put(usedPort,true);
} catch (IOException e) {
System.err.println("in sendToClient can't close sockt");
System.err.println(e.getMessage());
}
}发布于 2011-05-27 17:00:54
您是否尝试过在服务器套接字上调用setReuseAddress(true)?TCP状态机进入TIME_WAIT状态是正常的。有关详细解释,请查看here。
发布于 2011-05-27 11:42:56
这是因为在一些操作系统上实现了冷却时间。如果您等待一小段时间(例如几分钟),那么您应该能够再次访问该端口。
也就是说,在端口上打开和关闭服务器套接字并不是一个好主意。最好是打开它,并在必要时保持打开状态。然后在完成后将其关闭。不要打开/关闭/打开/关闭/打开/关闭...
发布于 2011-05-27 11:45:47
完成后只需关闭插座。它会自动关闭正在侦听的端口。完成后,切勿保持打开插座(端口)。
https://stackoverflow.com/questions/6147481
复制相似问题