/**
* 思路:创建通信的通道-->创建缓冲区-->将要发送的数据写入缓冲区-->网络通道将缓冲区中的数据发出
*/
@Test
public void clinet() throws IOException{
//1.创建网络通道
SocketChannel sChannel= SocketChannel.open(newInetSocketAddress("192.168.0.131", 8989));
//2.将通道设置成非阻塞式的
sChannel.configureBlocking(false);
//3.创建缓冲区
ByteBuffer buf= ByteBuffer.allocate(1024);
//4.从控制台输入数据
Scanner scan=newScanner(System.in);
while(scan.hasNext()){
Stringstr=scan.next();
//5.数据放入到缓冲区
buf.put(str.getBytes());
//6.切换读写模式
buf.flip();
//7.缓冲区数据通过网络通道发送出去
sChannel.write(buf);
//8.将发送出去的信息,从缓冲区中清除
buf.clear();
}
//9.关闭资源
sChannel.close();
}
/**
* 思路:服务端-->绑定监听端口-->打开选择器-->注册选择器-->获取监听事件-->获取建听建-->判断监听类型-->取消选择键
*/
@Test
public void server()throws IOException{
//1.获取服务端通道
ServerSocketChannel ssChannel= ServerSocketChannel.open();
//2.将服务端切换成非阻塞的
ssChannel.configureBlocking(false);
//3.将服务端绑定链接
ssChannel.bind(newInetSocketAddress(8989));
//4.打开选择器
Selectorselector= Selector.open();
//5.将选择器注册到服务端上,并且指定监听事件
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
//6.轮循式的获取选择器中所有注册的“准备就绪”的监听事件
while(selector.select()>0){
//7.获取当前选择器中所有注册的“选择键”
Iterator<SelectionKey> it=selector.selectedKeys().iterator();
while(it.hasNext()){
//8.获取准备就绪的事件
SelectionKey sk=it.next();
//9.判断具体是什么事件已经准备就绪
if(sk.isAcceptable()){
//10.若是接受就绪,获取客户端连接
SocketChannels Channel=ssChannel.accept();
//11.切换成非阻塞模式
sChannel.configureBlocking(false);
//12.将该通道注册到选择器上
sChannel.register(selector, SelectionKey.OP_READ);
}elseif(sk.isReadable()) {
//13.获取当前选择器上的读就绪的通道
SocketChannel sChannel= (SocketChannel)sk.channel();
//14.定义缓冲区
ByteBuffer buf= ByteBuffer.allocate(1024);
intlen= 0;
//15.将信息读入到缓冲区
while((len=sChannel.read(buf))>0){
buf.flip();
System.out.println(newString(buf.array(),0,len));
buf.clear();
}
}
//16.取消选择键
it.remove();
}
}
}
java nio 实现选择器客户端,服务端
最新推荐文章于 2021-12-17 00:37:13 发布