java socket端口关闭,调用ServerSocket.close()是否足以关闭端口?

I have some java code that looks similar to this:

private void startServer() throws IOException {

URLClassLoader classloader = null;

System.out.println("Opening server socket for listening on " + PORT_NUMBER);

try {

server = new ServerSocket(PORT_NUMBER);

server.setSoTimeout(10000);

connected = true;

System.out.println("Server is now listening on port " + PORT_NUMBER);

} catch (IOException e) {

System.err.println("Could not start server on port " + PORT_NUMBER);

e.printStackTrace();

connected = false;

}

while (connected) {

// Incoming request handler socket.

Socket socket = null;

try {

System.out.println("Waiting for client connection...");

// Block waiting for an incoming connection.

socket = server.accept();

if (socket == null) continue;

...and so on and so forth. When I call server.close() later on (I don't get any different behavior if I call socket.close() first), I don't get any errors, but netstat shows that the port is still being listened on. Should calling ServerSocket.close() be sufficient enough to free up the port on this system?

I am programming for a Java 1.4.2 microedition runtime. It is also worthy to note that I have this method being run in another thread, and I am trying to close the socket from its parent thread.

EDIT Here is the line from netstat, though I can assure you it is still being listened on, since if I start the Xlet again I get an exception with that port number.

tcp 0 0 *.2349 *.* LISTEN

解决方案

There are several things to consider. One of them is described by the following quotation from JavaDoc of ServerSocket

public void setReuseAddress(boolean on)

throws SocketException

Enable/disable the

SO_REUSEADDR socket option. When a TCP connection is closed the

connection may remain in a timeout state for a period of time after

the connection is closed (typically known as the TIME_WAIT state or

2MSL wait state). For applications using a well known socket address

or port it may not be possible to bind a socket to the required

SocketAddress if there is a connection in the timeout state involving

the socket address or port.

So it is kind of OK that the OS can still show that there is something going on after you close() the server socket. But if you going to open/close a server socket on the same port frequently you might hit a problem.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值