nio
package com.test.netty.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
* https://blog.youkuaiyun.com/chenssy/article/details/78703515
*/
public class NIOClient {
private SocketChannel socketChannel;
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
private Selector selector;
public NIOClient(String hostname, int port){
try {
socketChannel = SocketChannel.open();
// 设置为非阻塞 否则无法注册
socketChannel.configureBlocking(false);
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT);
// 一定要先注册在连接
socketChannel.connect(new InetSocketAddress(hostname, port));
System.out.printf("client init success,connect port:%s\r\n", port);
listen();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendMsg(){
try {
socketChannel.register(selector, SelectionKey.OP_WRITE);
} catch (ClosedChannelEx