您的位置:首页 > 其它

Socket关闭后端口仍然占用导致无法建立新的连接

2010-12-08 15:15 441 查看
目的:研究生高级计算机网络课程大作业--实现DV算法的router编写(J***A)



问题描述:

使用UDP协议进行通信,好不容易使线程Thread安全地关闭,却无法再次获取 同一个(IP,Port)
上的连接。

关于线程的安全终止这里再说两句,stop(), interrupt() ,destroy()

都是被废弃的、不安全的,最好让线程自动运行完毕。作者这里是通过直接向socket发出stop命令

实现的,阻塞的线程受到stop命令后设置 stop = true

然后可结束线程。



解决办法:

调用 socket.close()
之后必须调用 serversocket.close()
,这是因为socket对server发出断开连接请求时,只有在server回复ACK

后socket才会真正地释放连接,否则就会一直占用端口,导致无法重新建立连接,所以server也需要关闭。



部分代码如下:(关键在t.close()和l.close()




public void run() {
		// socket to listen on the command port
		ServerSocket l = null;
		// socket to represent the accepted connection
		Socket t = null;
		// the input and output streams associated with the connection
		ObjectOutputStream oos;
		ObjectInputStream ois;
		try {
			// listen on the command port
			l = new ServerSocket(port);
			System.out.println("CommandThread: Listening for commands on port " + port + "/n");
		} catch (Exception e) {
			System.out.println("CommandThread: Unable to open a listening socket on port: " + port + "/n");
			System.out.println("Quitting./n");
			return;
		}
		while (!stop) {
			try {
				// accept a connection
				t = l.accept();
			} catch (Exception e) {
				
				System.out.println("CommandThread: An I/O error occured while accepting a connection/n");
				System.out.println(e.getMessage());
				try {
					l.close();
					return;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
				
			try {
				// open the streams
				oos = new ObjectOutputStream(t.getOutputStream());
				ois = new ObjectInputStream(t.getInputStream());
				// read the command
				String in = (String) ois.readObject();
				String out;
				if(in.equals("stop")){
					this.stop = true;
					out = "receive the stop command!";
				}
				else{
					// execute the command and send the response
					out = r.executeCommand(in);
				}
				
				oos.writeObject(out);
				// close the streams and the connection
				ois.close();
				oos.close();
				t.close();
				
			} catch (Exception e) {
				System.out.println("CommandThread: An I/O error occured while communicating with COMMAND/n"+e.getMessage()+"/n");
				continue;
			}
		}
		try {
			l.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		System.out.println("CommandThread is stopped!/n");
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐