如果您持續關(guān)注OneCoder,您可能會(huì )問(wèn),在《Java NIO框架Netty教程(十四)- Netty中OIO模型(對比NIO)》中不是說(shuō)下節介紹的是,NIO和OIO中的worker處理方式嗎。這個(gè)一定會(huì )有的,只是在研究的過(guò)程中,OneCoder發(fā)現了之前遺留的文件傳輸的代碼,所以決定先完成它。
01 02 03 04 05 06 07 08 09 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 | /** * 文件傳輸接收端,沒(méi)有處理文件發(fā)送結束關(guān)閉流的情景 * * @author lihzh * @alia OneCoder * @blog http://www.coderli.com */public class FileServerHandler extends SimpleChannelHandler { private File file = new File("F:/2.txt"); private FileOutputStream fos; public FileServerHandler() { try { if (!file.exists()) { file.createNewFile(); } else { file.delete(); file.createNewFile(); } fos = new FileOutputStream(file); } catch (IOException e) { e.printStackTrace(); } } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer buffer = (ChannelBuffer) e.getMessage(); int length = buffer.readableBytes(); buffer.readBytes(fos, length); fos.flush(); buffer.clear(); }} |
01 02 03 04 05 06 07 08 09 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 | /** * 文件發(fā)送客戶(hù)端,通過(guò)字節流來(lái)發(fā)送文件,僅實(shí)現文件傳輸部分,<br> * 沒(méi)有對文件傳輸結束進(jìn)行處理<br> * 應該發(fā)送文件發(fā)送結束標識,供接受端關(guān)閉流。 * * @author lihzh * @alia OneCoder * @blog http://www.coderli.com */public class FileClientHandler extends SimpleChannelHandler { // 每次處理的字節數 private int readLength = 8; @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // 發(fā)送文件 sendFile(e.getChannel()); } private void sendFile(Channel channel) throws IOException { File file = new File("E:/1.txt"); FileInputStream fis = new FileInputStream(file); int count = 0; for (;;) { BufferedInputStream bis = new BufferedInputStream(fis); byte[] bytes = new byte[readLength]; int readNum = bis.read(bytes, 0, readLength); if (readNum == -1) { return; } sendToServer(bytes, channel, readNum); System.out.println("Send count: " + ++count); } } private void sendToServer(byte[] bytes, Channel channel, int length) throws IOException { ChannelBuffer buffer = ChannelBuffers.copiedBuffer(bytes, 0, length); channel.write(buffer); }} |
待發(fā)送的文件1.txt內容如下:

運行上述代碼,接受到的文件2.txt結果:

聯(lián)系客服