NIO 代码demo
1.服务端代码
public class NioServer {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",6666));
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true){
if(selector.select(1000)==0){
System.out.println("未检测出的连接");
continue;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(512));
}else if(selectionKey.isReadable()){
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
buffer.clear();
socketChannel.read(buffer);
System.out.println(new String(buffer.array()));
}
iterator.remove();
}
}
}
}
2.客户端代码
public class NioClient {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel=SocketChannel.open();
socketChannel.configureBlocking(false);
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 6666);
if (!socketChannel.connect(address)) {
while (!socketChannel.finishConnect()){
System.out.println("连接中,客户端可以进行其他工作");
}
String str="hello world!";
ByteBuffer wrap = ByteBuffer.wrap(str.getBytes());
socketChannel.write(wrap);
System.in.read();
}
}
}