我这篇文章想讲的是编程时如何正确关闭tcp连接。
首先给出一个网络上绝大部分的java nio代码示例:
服务端:
1首先实例化一个多路I/O复用器Selector
2然后实例化一个ServerSocketChannel
3ServerSocketChannel注册为非阻塞(channel.configureBlocking(false);)
4ServerSocketChannel注册到Selector,并监听连接事件(serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);)
5Selector开始轮询,如果监听到了isAcceptable()事件,就建立一个连接,如果监听到了isReadable()事件,就读数据。
6处理完或者在处理每个事件之前将SelectionKey移除出Selector.selectedKeys()
代码:
package qiuqi.main;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class NioServer {
public static void main(String[] args) throws IOException {
startServer();
}
static void startServer() throws IOException {
Selector selector = Selector.open();
ServerSoc