1 package cn.blog.test.NioTest;
2
3
4 import java.io.IOException;
5 import java.net.InetSocketAddress;
6 import java.nio.ByteBuffer;
7 import java.nio.channels.SelectionKey;
8 import java.nio.channels.Selector;
9 import java.nio.channels.SocketChannel;
10 import java.util.Iterator;
11
12 public class MyNioClient {
13 private Selector selector; //创建一个选择器
14 private final static int port = 8686;
15 private final static int BUF_SIZE = 10240;
16 private static ByteBuffer byteBuffer = ByteBuffer.allocate(BUF_SIZE);
17
18 private void initClient() throws IOException {
19 this.selector = Selector.open();
20 SocketChannel clientChannel = SocketChannel.open();
21 clientChannel.configureBlocking(false);
22 clientChannel.connect(new InetSocketAddress(port));
23 clientChannel.register(selector, SelectionKey.OP_CONNECT);
24 while (true){
25 selector.select();
26 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
27 while (iterator.hasNext()){
28 SelectionKey key = iterator.next();
29 iterator.remove();
30 if (key.isConnectable()){
31 doConnect(key);
32 }else if (key.isReadable()){
33 doRead(key);
34 }
35 }
36 }
37 }
38
39 public void doConnect(SelectionKey key) throws IOException {
40 SocketChannel clientChannel = (SocketChannel) key.channel();
41 if (clientChannel.isConnectionPending()){
42 clientChannel.finishConnect();
43 }
44 clientChannel.configureBlocking(false);
45 String info = "服务端你好!!";
46 byteBuffer.clear();
47 byteBuffer.put(info.getB