本文介绍了使用服务器套接字后如何关闭端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我创建一个带有某些端口的 ServerSocket 实例.完成后,我关闭了套接字,但是当我尝试在同一端口上创建新的 ServerSocket 时,它将抛出:

In my application I create a ServerSocket instance with some port. After I am finished, I close the socket, but when I try to make a new ServerSocket on the same port, it throws:

"java.net.BindException: Address already in use"

如果我使用其他端口创建 ServerSocket ,那么它将起作用.

If I create the ServerSocket with a different port, then it works.

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

推荐答案

您是否尝试过在服务器套接字上调用 setReuseAddress(true)?TCP状态机进入 TIME_WAIT 状态是正常的.有关详细说明,请此处.

Have you tried calling setReuseAddress(true) on the server socket? It's normal for the TCP state machine to enter TIME_WAIT state. For detailed explanation look here.

这篇关于使用服务器套接字后如何关闭端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 19:34