9NIO--阻塞式
Posted mrchengs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了9NIO--阻塞式相关的知识,希望对你有一定的参考价值。
使用NIO完成网络通信的三个核心:
1、通道(Channel):负责连接
java.nio.channels.Channel接口:
SelectableChannel抽象类:有一下几个实现类
SocketChannel TCP
ServerSocketChannel TCP
DategramChannel UDP
Pipe.SinkChannel
Pipe.SourceChannel
2、缓冲区(Buffer):负责数据的存取
3、选择器(Selector):式SelectableChannel的多路复用器,用于监控SelectableChannel的IO状况
代码实例:
//服务端 @Test public void server() throws IOException{ //1、获取异常 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //2、绑定连接 serverSocketChannel.bind(new InetSocketAddress(8081)); //3、获取客户端连接的通道 SocketChannel sockChannel = serverSocketChannel.accept(); //4、分配指定大小的缓冲区 ByteBuffer buf = ByteBuffer.allocate(1024); //5、接收客户端的数据保存到本地 FileChannel outChannel = FileChannel.open(Paths.get("d:\\\\aaa.jpg"), StandardOpenOption.WRITE ,StandardOpenOption.CREATE,StandardOpenOption.READ); while(sockChannel.read(buf) != -1){ buf.flip(); outChannel.write(buf); buf.clear(); } serverSocketChannel.close(); outChannel.close(); sockChannel.close(); }
//客户端 @Test public void client(){ //1、获取通道 SocketChannel socketChannel = null; FileChannel inChannel = null; try { socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8081)); //2、分配指定大小的缓冲区 ByteBuffer buf = ByteBuffer.allocate(1024); //3、读取本地文件,并且发送 inChannel = FileChannel.open(Paths.get("d:\\\\a.jpg"), StandardOpenOption.READ); while(inChannel.read(buf) != -1){ buf.flip(); socketChannel.write(buf); buf.clear(); } } catch (IOException e) { e.printStackTrace(); }finally { try { socketChannel.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { inChannel.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
先开启服务端在开启客户端:
以上是关于9NIO--阻塞式的主要内容,如果未能解决你的问题,请参考以下文章