Java 服务器套接字不重用地址 [英] Java server socket doesn't reuse address

查看:43
本文介绍了Java 服务器套接字不重用地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 linux 中使用服务器套接字,我需要在 time_wait TCP 状态到期之前关闭它并重新打开.我在绑定之前设置了服务器套接字的重用地址选项,但它仍然抛出一个 BindException.我也试过这个 http://meteatamel.wordpress.com/2010/12/01/socket-reuseaddress-property-and-linux/ 但它仍然不起作用.

I am using a server socket in linux and I need to close it and reopen before the time_wait TCP status expires. I set the reuse address option of the server socket before the binding but it still throws a BindException. I also tried this http://meteatamel.wordpress.com/2010/12/01/socket-reuseaddress-property-and-linux/ but it still doesn't work.

要打开我使用的服务器套接字:

To open a server socket i use:

ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(12345));

并关闭:

ss.close();

在绑定调用时抛出地址已在使用中"BindException.

The "Address already in use" BindException is throwed at the bind call.

此代码生成异常:

for (int i = 0; i < 2; i++) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final ServerSocket ss = new ServerSocket();
                    ss.setReuseAddress(true);
                    ss.bind(new InetSocketAddress(12345));
                    Socket s = ss.accept();
                    System.out.println((char) s.getInputStream().read());
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Thread.sleep(500);
        Socket s = new Socket("localhost", 12345);
        s.getOutputStream().write('c');
    }

推荐答案

你设置重用 before 绑定而不是在你得到异常之后.

You set reuse before binding not after you get an exception.

ServerSocket ss = new ServerSocket(); // don't bind just yet
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(12345)); // can bind with reuse= true

这在 Windows 7 和 RHEL 5.x 上运行没有错误

This runs without error on Windows 7 and RHEL 5.x

for (int i = 0; i < 1000; i++) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                final ServerSocket ss = new ServerSocket();
                ss.setReuseAddress(true);
                ss.bind(new InetSocketAddress(12345));
                Socket s = ss.accept();
                System.out.println((char) s.getInputStream().read());
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
    Thread.sleep(50);
    Socket s = new Socket("localhost", 12345);
    s.getOutputStream().write('c');
    t.join();
}

这篇关于Java 服务器套接字不重用地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆