首页 > 代码库 > NIO传输文件

NIO传输文件

 客户端:

 1 package com.gs.practice.nio; 2  3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.net.InetSocketAddress; 6 import java.nio.ByteBuffer; 7 import java.nio.channels.ClosedChannelException; 8 import java.nio.channels.FileChannel; 9 import java.nio.channels.SelectionKey;10 import java.nio.channels.Selector;11 import java.nio.channels.SocketChannel;12 import java.util.Set;13 14 /**15  * Copyright (C),HTF<br>16  * 客户端上传图片17  * 18  * @author muzhongjiang19  * @date 2014年9月5日20  */21 public class FileClient {22     private int port = 8000;23     private static ByteBuffer sendBuffer = ByteBuffer.allocate(1024);// 发送数据缓冲区24     private InetSocketAddress SERVER;25     private static Selector selector;26     private static SocketChannel client;27 28     public FileClient() throws Exception {29         SERVER = new InetSocketAddress("localhost", port);30         init();31     }32 33     /**34      * 初始化35      */36     private void init() throws Exception {37         SocketChannel socketChannel = SocketChannel.open();38         socketChannel.configureBlocking(false);39         selector = Selector.open();40         socketChannel.register(selector, SelectionKey.OP_CONNECT);41         socketChannel.connect(SERVER);42         this.listener();43     }44 45     /**46      * 监听器47      */48     private void listener() throws IOException, ClosedChannelException, Exception {49         while (true) {50             selector.select();51             Set<SelectionKey> keySet = selector.selectedKeys();52             for (final SelectionKey key : keySet) {53                 if (key.isConnectable()) {54                     client = (SocketChannel) key.channel();55                     client.finishConnect();56                     client.register(selector, SelectionKey.OP_WRITE);57 58                 } else if (key.isWritable()) {59                     this.sendFile(client);60                 }61             }62             keySet.clear();63         }64     }65 66     private void sendFile(SocketChannel client) throws Exception {67         FileInputStream fis = null;68         FileChannel channel = null;// 传输不同的数据选择对应的“通道”69         fis = new FileInputStream("E:\\1.txt");70         channel = fis.getChannel();71         int i = 1;72         int count = 0;73         while ((count = channel.read(sendBuffer)) != -1) {74             sendBuffer.flip();75             int send = client.write(sendBuffer);76             System.out.println("i===========" + (i++) + "   count:" + count + " send:" + send);77             while (send == 0) {// 传输失败( 服务器端可能因为缓存区满,而导致数据传输失败,需要重新发送)78                 Thread.sleep(10);79                 send = client.write(sendBuffer);80                 System.out.println("i重新传输====" + i + "   count:" + count + " send:" + send);81             }82             sendBuffer.clear();83         }84         channel.close();85         fis.close();86         client.close();87     }88 89     public static void main(String[] args) throws Exception {90         new FileClient();91     }92 }
View Code

 

 服务端:

  1 package com.gs.practice.nio;  2   3 import java.io.FileNotFoundException;  4 import java.io.FileOutputStream;  5 import java.io.IOException;  6 import java.net.InetSocketAddress;  7 import java.net.ServerSocket;  8 import java.nio.ByteBuffer;  9 import java.nio.channels.ClosedChannelException; 10 import java.nio.channels.FileChannel; 11 import java.nio.channels.SelectionKey; 12 import java.nio.channels.Selector; 13 import java.nio.channels.ServerSocketChannel; 14 import java.nio.channels.SocketChannel; 15 import java.util.Set; 16 /** 17  * Copyright (C),HTF<br> 18  * 图片服务器端 19  *  20  * @author muzhongjiang 21  * @date 2014年9月5日 22  */ 23 public class FileServer { 24     private int port = 8000; 25     private static ByteBuffer revBuffer = ByteBuffer.allocate(1024);// 接收数据缓冲区 26     private static Selector selector; 27     private static FileOutputStream fout; 28     private static FileChannel ch; 29  30     public FileServer() throws Exception { 31         init(); 32     } 33  34     /** 35      * 初始化 36      */ 37     private void init() throws Exception { 38         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 39         serverSocketChannel.configureBlocking(false); 40         ServerSocket serverSocket = serverSocketChannel.socket(); 41         serverSocket.bind(new InetSocketAddress(port)); 42         selector = Selector.open(); 43         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); 44         System.out.println("server start on port:" + port); 45         this.listener(); 46     } 47  48     /** 49      * 监听器 50      */ 51     private void listener() throws IOException, ClosedChannelException, FileNotFoundException { 52         while (true) { 53             selector.select();// 返回值为本次触发的事件数 54             Set<SelectionKey> selectionKeys = selector.selectedKeys(); 55  56             for (SelectionKey key : selectionKeys) { 57                 ServerSocketChannel server = null; 58                 SocketChannel client = null; 59                 int count = 0; 60                 if (key.isAcceptable()) { 61                     server = (ServerSocketChannel) key.channel(); 62                     System.out.println("有客户端连接进入=============)"); 63                     client = server.accept(); 64                     client.configureBlocking(false); 65                     client.register(selector, SelectionKey.OP_READ); 66                     fout = new FileOutputStream("E:\\" + client.hashCode() + ".txt"); 67                     ch = fout.getChannel(); 68                 } else if (key.isReadable()) { 69                     client = (SocketChannel) key.channel(); 70                     revBuffer.clear(); 71                     count = client.read(revBuffer); 72                     int k = 0; 73                     // 循环读取缓存区的数据, 74                     while (count > 0) { 75                         System.out.println("k=" + (k++) + " 读取到数据量:" + count); 76                         revBuffer.flip(); 77                         ch.write(revBuffer); 78                         fout.flush(); 79                         revBuffer.clear(); 80                         count = client.read(revBuffer); 81                     } 82                     if (count == -1) { 83                         client.close(); 84                         ch.close(); 85                         fout.close(); 86                     } 87                 } else if (key.isWritable()) { 88                     System.out.println("selectionKey.isWritable()"); 89                 } 90             } 91             System.out.println("=======selectionKeys.clear()"); 92             selectionKeys.clear(); 93  94         } 95     } 96  97     public static void main(String[] args) throws Exception { 98         new FileServer(); 99     }100 }
View Code

 

NIO传输文件