Java NIO 服务器与客户端实现文件下载

简介:

写在前面

对于Java NIO已经学习了一段时间了,周末实践了下,折腾了一天,总算对NIO的理论,有了一个感性的认识。下面的实践是:服务器与客户端都采用NIO的方式来实现文件下载。对于传统的SOCKET BIO方式,服务器端会为每个连接上的客户端分配一个Worker线程来进行doWork,而NIO SERVER却没有为每个Socket链接分配线程的必要了,避免了大量的线程所需的上下文切换,借助NIO提供的Selector机制,只需要一个或者几个线程来管理成百上千的SOCKET连接。那么下面我们就来看看吧!


文件下载辅助类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
  * 这个类的基本思路是,读取本地文件到缓冲区
  * 因为通道只能操作缓冲区
  */
class  DownloadFileProcesser  implements  Closeable{
private  ByteBuffer buffer = ByteBuffer.allocate( 8  1024 );
private  FileChannel fileChannel ;
public  DownloadFileProcesser() {
     try {
         FileInputStream fis =  new  FileInputStream( "e:/tmp/Shell学习笔记.pdf" );
         fileChannel = fis.getChannel();
     } catch (Exception e){
         e.printStackTrace();
     }
}
public  int  readFile2Buffer()  throws  IOException{
     int  count =  0 ;
     buffer.clear();
     count = fileChannel.read(buffer);
     buffer.flip();
     return  count;
}
public  ByteBuffer getByteBuffer(){
     return  buffer;
}
@Override
public  void  close()  throws  IOException {
     fileChannel.close();
}
 
}


服务端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public  class  ServerMain {
 
public  static  void  main(String[] args)  throws  IOException {
     ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
     serverSocketChannel.configureBlocking( false );
     serverSocketChannel.socket().bind( new  InetSocketAddress( 8887 ));
     Selector selector = Selector.open();
     serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
 
     while  ( true ) {
         selector.select();
         Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
         while  (iterator.hasNext()) {
         SelectionKey s = iterator.next();
         // 如果客户端有连接请求
         if  (s.isAcceptable()) {
         System.out.println( "客户端连接请求.." );
         ServerSocketChannel ssc = (ServerSocketChannel) s.channel();
         SocketChannel sc = ssc.accept();
         sc.configureBlocking( false );
         sc.register(selector, SelectionKey.OP_READ);
         }
         // 如果客户端有发送数据请求
         if  (s.isReadable()) {
         System.out.println( "接受客户端发送过来的文本消息..." );
         //这里拿出的通道就是ACCEPT上注册的SocketChannel通道
         SocketChannel sc = (SocketChannel) s.channel();
         //要读取数据先要准备好BUFFER缓冲区
         ByteBuffer buffer = ByteBuffer.allocate( 8  1024 );
         //准备BYTE数组,形成输出
         sc.read(buffer);
         byte [] clientByteInfo =  new  byte [buffer.position()];
         buffer.flip();
         buffer.get(clientByteInfo);
         System.out.println( "服务器端收到消息:"  new  String(clientByteInfo, "utf-8" ));
         //CLIENT下一步的动作就是读取服务器端的文件,因此需要注册写事件
         SelectionKey selectionKey = sc.register(selector, SelectionKey.OP_WRITE);
         //在这个selectionKey上绑定一个对象,以供写操作时取出进行处理
         DownloadFileProcesser downloadFileProcesser =  new  DownloadFileProcesser();
         selectionKey.attach(downloadFileProcesser);
         }
     
     // 如果客户端有下载文件数据请求
     if  (s.isWritable()) {
     //这里把attachment取出进行写入操作
     DownloadFileProcesser downloadFileProcesser = (DownloadFileProcesser)s.attachment();
     int  count = downloadFileProcesser.readFile2Buffer();
    
     if (count <=  0 ){
         System.out.println( "客户端下载完毕..." );
         //关闭通道
         s.channel().close();
         downloadFileProcesser.close();
     } else {
         //需要注意的是我们这里并没有出现常见的while写的结构,这是为何?
         //因为client其实不断的在read操作,从而触发了SELECTOR的不断写事件!
         SocketChannel sc = (SocketChannel)s.channel();
         sc.write(downloadFileProcesser.getByteBuffer());
      }
    }
         iterator.remove();
   }
  }
  }
}


客户端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class  Client4DownloadFile  implements  Runnable{
     
     //标示
     private  String name;
     private  FileChannel fileChannel;
     public  Client4DownloadFile(String name , RandomAccessFile randomAccessFile){
     this .name = name;
     this .fileChannel = randomAccessFile.getChannel(); 
     }
     
     private  ByteBuffer buffer = ByteBuffer.allocate( 8  1024 );
 
     @Override
public  void  run() {
try  {
     SocketChannel sc = SocketChannel.open();
     Selector selector = Selector.open();
     sc.configureBlocking( false );
     sc.register(selector, SelectionKey.OP_CONNECT);
     sc.connect( new  InetSocketAddress( "127.0.0.1" , 8887 ));
    
     while ( true ){
         selector.select();
         Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        
         while (iterator.hasNext()){
         SelectionKey s = iterator.next();
         if (s.isConnectable()){
         System.out.println( "客户端["  + name +  "]已经连接上了服务器..." );
         SocketChannel sc2 = (SocketChannel)s.channel();
         if (sc2.isConnectionPending() && sc2.finishConnect()){
         sc2.configureBlocking( false );
         String msg =  "Thread-"  + name +  " send message!" ;
         byte [] b = msg.getBytes( "utf-8" );
         sc2.write(ByteBuffer.wrap(b));
         System.out.println( "客户端["  + name +  "]给服务器端发送文本消息完毕..." );
         sc2.register(selector, SelectionKey.OP_READ);
     }
     }
     
     if (s.isReadable()){
         SocketChannel sc3 = (SocketChannel)s.channel();
         buffer.clear();
         int  count = sc3.read(buffer);
         if (count <=  0 ){
         s.cancel();
         System.out.println( "Thread "  + name +  " 下载完毕..." );
     }
     while (count >  0 ){
         buffer.flip();
         fileChannel.write(buffer);
         count = sc3.read(buffer);
         }
     }
         iterator.remove();
     }
    }
   catch  (IOException e) {
         e.printStackTrace();
   }
}
}



1
2
3
4
5
6
7
8
9
10
public  class  ClientMain {
     public  static  void  main(String[] args)  throws  FileNotFoundException{
         for ( int  i =  0  ; i <  10  ; i++){
             File file =  new  File( "e:/tmp/"  + i +  ".pdf" );
             RandomAccessFile raf =  new  RandomAccessFile(file, "rw" );
             Client4DownloadFile client4DownloadFile =  new  Client4DownloadFile( ""  + i, raf);
             new  Thread(client4DownloadFile).start();
         }
     }
}


wKioL1Z2IYyykWSeAAEVYbJjp3U161.png


wKiom1Z2I_6ScuIpAABGN4wDSSw847.png


本文转自zfz_linux_boy 51CTO博客,原文链接:http://blog.51cto.com/zhangfengzhe/1726488,如需转载请自行联系原作者

相关文章
|
1月前
|
存储 Java 数据处理
|
1月前
|
Java API
java中IO与NIO有什么不同
java中IO与NIO有什么不同
|
1月前
|
JSON NoSQL Java
【Redis】2、Redis 的 Java 客户端(Jedis 和 SpringDataRedis)
【Redis】2、Redis 的 Java 客户端(Jedis 和 SpringDataRedis)
44 0
|
3天前
|
Java API Apache
ZooKeeper【基础 03】Java 客户端 Apache Curator 基础 API 使用举例(含源代码)
【4月更文挑战第11天】ZooKeeper【基础 03】Java 客户端 Apache Curator 基础 API 使用举例(含源代码)
21 11
|
4天前
|
监控 Java 开发者
深入理解 Java 网络编程和 NIO
【4月更文挑战第19天】Java网络编程基于Socket,但NIO(非阻塞I/O)提升了效率和性能。NIO特点是非阻塞模式、选择器机制和缓冲区,适合高并发场景。使用NIO涉及通道、选择器和事件处理,优点是高并发、资源利用率和可扩展性,但复杂度、错误处理和性能调优是挑战。开发者应根据需求选择是否使用NIO,并深入理解其原理。
|
1月前
|
监控 Java 网络安全
|
2月前
|
Java
java上传、下载、预览、删除ftp服务器上的文件
java上传、下载、预览、删除ftp服务器上的文件
|
2月前
|
移动开发 编解码 网络协议
用Java的BIO和NIO、Netty来实现HTTP服务器(三) 用Netty实现
用Java的BIO和NIO、Netty来实现HTTP服务器(三) 用Netty实现
|
4月前
|
存储 监控 Java
Java输入输出:什么是NIO(New I/O)?
Java输入输出:什么是NIO(New I/O)?
33 1
|
6月前
|
存储 Java API
Java NIO+示例代码
Java NIO(New IO)是 JDK 1.4 引入的一组新的 I/O API,用于支持非阻塞式 I/O 操作。相比传统的 Java IO API,NIO 提供了更快、更灵活的 I/O 操作方式,可以用于构建高性能网络应用程序。 Java NIO 的主要组成部分包括: 1. Channel:通道是一个在应用程序和文件、网络套接字之间的连接。可以通过通道来进行数据的读取和写入。 2. Buffer:缓冲区是一个容器,用于存储数据。在 NIO 中,所有的数据读取和写入都是通过缓冲区进行的。 3. Selector:选择器用于监听多个 NIO 通道的事件,如读写事件。当某个通道发生事件时,选
52 0

热门文章

最新文章