这篇博客讲的很细
https://www.jianshu.com/p/191041073919
public class client2 {
public static void main(String[] args)throws Exception {
client();
}
public static void client()throws Exception{
//1创建网络套接字
SocketChannel socketChannel = SocketChannel.open
(new InetSocketAddress("127.0.0.1",8989));
//2切换为非阻塞模式
socketChannel.configureBlocking(false);
//3建立缓冲区
ByteBuffer buffer=ByteBuffer.allocate(1024);
//4发送数据给服务器
Scanner scanner =new Scanner(System.in);
while (scanner.hasNext()) {
String str = scanner.next();
buffer.put((new Date().toString()+"\n"+str).getBytes());
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
}
//5关闭通道
socketChannel.close();
}
}
public class Server2 {
public static void main(String[] args)throws Exception {
server();
}
public static void server()throws Exception{
//1 打开服务器端套接字通信
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
//2切换为非阻塞模式
serverSocketChannel.configureBlocking(false);
//3绑定端口
serverSocketChannel.bind(new InetSocketAddress(8989));
//4获取选择器
Selector selector =Selector.open();
//5将通道注册到选择器中,并选择进行哪种操作,监听接收事件
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
//6 轮询选择器上已经准备的事件
while (selector.select()>0){
//获取当前选择中所有注册的选择键
Iterator<SelectionKey> iterator=selector.selectedKeys().iterator();
//迭代器
while (iterator.hasNext()){
//获取准备就绪的事件
SelectionKey selectionKey=iterator.next();
//判断是哪种事件的就绪
if(selectionKey.isAcceptable()){
//获取客户端的套接字通道
SocketChannel socketChannel=serverSocketChannel.accept();
//切换为非阻塞模式
socketChannel.configureBlocking(false);
//注入到选择器中,操作为读
socketChannel.register(selector,SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){
SocketChannel socketChannel=(SocketChannel) selectionKey.channel();
//得到一个缓冲区
int len=0;
ByteBuffer buffer=ByteBuffer.allocate(1024);
while ((len=socketChannel.read(buffer))>0){
buffer.flip();
System.out.println(new String(buffer.array(),0,len));
buffer.clear();
}
}
//取消选择键
iterator.remove();
}
}
}
}