#NIO的服务端开发流程:
NIO的客户端编程
@Test
public void servi(){
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open ();
serverSocketChannel.bind (new InetSocketAddress (8893));
System.out.println ("绑定成功");
serverSocketChannel.configureBlocking (false);
Selector selector = Selector.open ();
serverSocketChannel.register (selector , SelectionKey.OP_ACCEPT);
while (selector.select ()>0) {
Iterator<SelectionKey> iterator = selector.selectedKeys ().iterator ();
while (iterator.hasNext ()) {
SelectionKey selectionKey = iterator.next ();
iterator.remove ();
if (selectionKey.isAcceptable ()) {
System.out.println ("有事件要发生 ");
ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) selectionKey.channel ();
SocketChannel socketChannel = serverSocketChannel1.accept ();
socketChannel.configureBlocking (false);
socketChannel.register (selector , SelectionKey.OP_READ);
}
if (selectionKey.isReadable ()) {
System.out.println ("有读事件发生");
SocketChannel channel = (SocketChannel) selectionKey.channel ();
ByteBuffer allocate = ByteBuffer.allocate (1024);
int read = channel.read (allocate);
if (read == -1){
channel.close ();
}
allocate.flip ();
byte[] bytes = new byte[allocate.remaining ()];
allocate.get (bytes);
String s = new String (bytes);
System.out.println (s);
}
}
}
} catch (IOException e) {
e.printStackTrace ();
}
}
@Test
public void cli() {
try {
SocketChannel socketChannel = SocketChannel.open ();
socketChannel.configureBlocking (false);
Selector selector = Selector.open ();
if (!socketChannel.connect (new InetSocketAddress ("127.0.0.1" , 8893))){
socketChannel.register (selector , SelectionKey.OP_CONNECT);
selector.select ();
Iterator<SelectionKey> iterator = selector.selectedKeys ().iterator ();
while (iterator.hasNext ()) {
SelectionKey selectionKey = iterator.next ();
iterator.remove ();
if (selectionKey.isConnectable ()){
SocketChannel socketChannel1 = (SocketChannel) selectionKey.channel ();
socketChannel1.finishConnect ();
}
}
}
System.out.println ("连接成功");
ByteBuffer buffer = ByteBuffer.allocate (1024);
buffer.put ("hello".getBytes ());
buffer.flip ();
socketChannel.write (buffer);
socketChannel.close ();
} catch (IOException e) {
e.printStackTrace ();
}
}
}