Java网络编程从入门到精通(29):服务端Socket的选项
2009-09-22 00:00:00 来源:WEB开发网package server;
import java.net.*;
public class TestReuseAddr1
{
public static void main(String[] args) throws Exception
{
ServerSocket serverSocket1 = new ServerSocket(1234);
System.out.println(serverSocket1.getReuseAddress());
ServerSocket serverSocket2 = new ServerSocket();
serverSocket2.setReuseAddress(true);
serverSocket2.bind(new InetSocketAddress(1234));
ServerSocket serverSocket3 = new ServerSocket();
serverSocket3.setReuseAddress(true);
serverSocket3.bind(new InetSocketAddress(1234));
}
}
运行结果:false
在上面代码中第一次绑定端口1234,因此,serverSocket1对象无需设置SO_REUSEADDR选项(这个选项在大多数操作系统上的默认值是false)。而serverSocket2和serverSocket3并不是第一次绑定端口1234,因此,必须设置这两个对象的SO_REUSEADDR值为true。在设置SO_REUSEADDR选项时要注意,必须在ServerSocket对象绑定端口之前设置这个选项。
也许有的读者可能有这样的疑问。如果多个ServerSocket对象同时绑定到一个端口上,那么当客户端向这个端口发出请求时,该由哪个ServerSocket对象来接收客户端请求呢?在给出答案之前,让我们先看看下面的代码的输出结果是什么。
package server;
import java.net.*;
public class TestReuseAddr2 extends Thread
{
String s;
public void run()
{
try
{
ServerSocket serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(1234));
Socket socket = serverSocket.accept();
System.out.println(s + ":" + socket);
socket.close();
serverSocket.close();
}
catch (Exception e)
{
}
}
public TestReuseAddr2(String s)
{
this.s = s;
}
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
new TestReuseAddr2("ServerSocket" + i).start();
}
}
更多精彩
赞助商链接