NIO可谓陈词旧调,不值一提. 但之前都是泛泛而谈, 现在深入应用才知道秘诀所在. 对于SocketChannel有read()与write(),但由于"非阻塞IO"本质, 这二个方法的返回值提示其字符数目. 说白点, 就是你得有个措施解决可能一次不能完成的操作. 否则, 你在服务端的数据会莫名其妙地乱码, 莫名其妙地不见...
还有另一个关键之处就是Buffer的应用, 重用Buffer的时候务必注意, position, limit的标点. 下面是实质源码:
private void onAccept(SelectionKey key) {

logger.debug("处理Accept事件");
  SocketChannel sc = null;
  try {
   ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
   sc = ssc.accept();
   /* 判断其是否可以连接 */
   String client = ((InetSocketAddress) sc.socket().getRemoteSocketAddress()).getAddress().getHostAddress();
   if (config.senders.containsKey(client)) {
    /* 前缀格式<系统>+<服务器IP>+ */
    String prefix = config.senders.getProperty(client);
    sc.configureBlocking(false);
    sc.register(selector, SelectionKey.OP_READ, new AttachObject(encoder.encode(prefix.toString(), config.charset)));
    logger.info(String.format("发送者%s连接成功, 记录前缀:%s", client, prefix));
   } else {
    logger.info(String.format("发送者%s连接拒绝", client));
    sc.close();
   }
  } catch (Exception e) {
   logger.error("处理Accept事件错误!", e);
   if (sc != null) {
    try {
     sc.close();
    } catch (IOException e1) {
     logger.error("关闭异常Socket错误!", e1);
    }
   }
  }
}
使用InetAddress.getHostAddress()才能获取实际意义上的IP.
private void onRead(SelectionKey key) {

/* 必须注意NIO可能无法一次接收完全部数据 */
  logger.debug("处理Read事件");
  int ret = 0;
  int size = 0;
  SocketChannel sc = null;
  try {
   sc = (SocketChannel) key.channel();
   AttachObject attach = (AttachObject) key.attachment();
   if (attach.idx < 4) {
    ret = sc.read(attach.sizeBuf);
    if (ret == -1) {
     logger.debug("客户端输入流已关闭!");
     sc.close();
     sc = null;
     return;
    } else {
     attach.idx += ret;
    }
   }

if (attach.idx == 4) {
    attach.sizeBuf.flip();
    size = attach.sizeBuf.getInt();
    attach.tot = 4 + size;
    if (attach.dataBuf.capacity() < size) {
     attach.dataBuf = ByteBuffer.allocate(size);
    }else {
     attach.dataBuf.limit(size);/* 必须限制可读字节数,否则可能读多 */
    }
   }

if (attach.idx >= 4 && attach.idx < attach.tot) {
    ret = sc.read(attach.dataBuf);
    if (ret == -1) {
     logger.debug("客户端输入流已关闭!");
     sc.close();
     sc = null;
     return;
    } else {
     attach.idx += ret;
    }
   }

if (attach.idx == attach.tot) {
    attach.dataBuf.flip();
    cache.put((byte[]) attach.attach, attach.dataBuf.array(), 0, attach.dataBuf.limit());
    attach.reset();
   }

} catch (Exception e) {
   logger.error("处理Read事件错误!", e);
   if (sc != null) {
    try {
     sc.close();
    } catch (IOException e1) {
     logger.error("关闭异常Socket错误!", e1);
    }
   }
  }
}
每个Key要有独享的Attachment来保存中间信息, 使用Buffer读取或写入字节务必注意其返回值. 必须在字节数完全读完才能去解码.
public void run() {
   ByteBuffer sizeBuf = ByteBuffer.allocate(4);
   int idx = 0;
   int tot = 0;
   LinkedList<byte[]> batch = new LinkedList<byte[]>();
   try {
    SocketChannel sc = SocketChannel.open();
    sc.connect(new InetSocketAddress(outer.config.receiverHost, outer.config.receiverPort));
    outer.scList.add(sc);
    while (!Thread.currentThread().isInterrupted()) {
     batch.clear();
     if (outer.cache.get(batch, outer.config.senderBatchSize, true) > 0) {
      for (byte[] data : batch) {
       /* 必须注意,NIO有可能不会一次写完Buffer的字节 */
       idx = 0;
       tot = 4 + data.length;

sizeBuf.clear();
       sizeBuf.putInt(data.length);
       sizeBuf.flip();
       do {
        idx += sc.write(sizeBuf);
       } while (idx < 4);

ByteBuffer dataBuf = ByteBuffer.wrap(data);
       do {
        idx += sc.write(dataBuf);
       } while (idx < tot);
      }
     }
    }
   } catch (IOException e) {
    throw new RuntimeException(e);
   }
  }
使用Buffer写字节数据也必须注意其返回值, 在未达到预期时, 使用循环继续.
以上三个方法是Socket NIO的关键所在. 当你接收到的数据乱码的时候,你会想起这些...

Java之NIO传输数据的更多相关文章

  1. JAVA bio nio aio

    [转自]http://qindongliang.iteye.com/blog/2018539 在高性能的IO体系设计中,有几个名词概念常常会使我们感到迷惑不解.具体如下: 序号 问题 1 什么是同步? ...

  2. java的nio之:java的nio系列教程之buffer的概念

    一:java的nio的buffer==>Java NIO中的Buffer用于和NIO通道Channel进行交互.==>数据是从通道channel读入缓冲区buffer,从缓冲区buffer ...

  3. java的nio之:java的nio系列教程之channel的概念

    一:java的nio的channel Java NIO的通道类似流,但又有些不同: ==>既可以从通道中读取数据,又可以写数据到通道.但流的读写通常是单向的. ==>通道可以异步地读写. ...

  4. java的nio之:java的nio系列教程之概述

    一:java的nio的核心组件?Java NIO 由以下几个核心部分组成: ==>Channels ==>Buffers ==>Selectors 虽然Java NIO 中除此之外还 ...

  5. java之NIO编程

    所谓行文如编程,随笔好比java文件,文章好比类,参考文献是import,那么目录就是方法定义. 本篇文章处在分析thrift的nonblocking server之前,因为后者要依赖该篇文章的知识. ...

  6. 输入和输出--java的NIO

    Java的NIO 实际开发中NIO使用到的并不多,我并不是说NIO使用情景不多,是说我自己接触的并不是很多,前面我在博客园和CSDN上转载了2篇别人写的文章,这里来大致总结下Java的NIO,大概了解 ...

  7. JAVA 探究NIO

    事情的开始 1.4版本开始,java提供了另一套IO系统,称为NIO,(New I/O的意思),NIO支持面向缓冲区的.基于通道的IO操作. 1.7版本的时候,java对NIO系统进行了极大的扩展,增 ...

  8. 理解Java的NIO

    同步与阻塞 同步和异步是针对应用程序和内核的交互而言的. 同步:执行一个操作之后,进程触发IO操作并等待(阻塞)或者轮询的去查看IO的操作(非阻塞)是否完成,等待结果,然后才继续执行后续的操作. 异步 ...

  9. Java通过NIO实现快速文件拷贝的代码

    将内容过程重要的内容片段做个记录,下面的内容段是关于Java通过NIO实现快速文件拷贝的内容. public static void fileCopy( File in, File out ) thr ...

随机推荐

  1. SQL where 1=1的作用

    浅谈where 1=1 1.简单理解的话where 1=1 永真, where 1<>1 永假 2.1<>1 的用处:     用于只取结构不取数据的场合     例如:    ...

  2. 学习总结 java 输入输出流

    思维导图 代码实际演示 package com.hanqi.io; import java.io.*; public class Test1 { public static void main(Str ...

  3. No.009 Palindrome Number

    9. Palindrome Number Total Accepted: 136330 Total Submissions: 418995 Difficulty: Easy Determine whe ...

  4. 【spring 4】AOP:动态代理

    一.动态代理简介 动态代理与普通代理相比较,最大的好处是接口中声明的所有方法都被转移到一个集中的方法中处理(invoke),这样,在接口方法数量比较多的时候,我们可以进行灵活处理,而不需要像静态代理那 ...

  5. ArcGIS10.2最新全套下载地址

    http://www.tuicool.com/articles/VfaMfy 免责声明: 该链接来自于哥伦比亚大学或者牛津大学的网站链接, 下载 软件之前确保有正版的软件授权 ,本博客只是转载了网站链 ...

  6. Java 对字符反转操作。

    //把一段字符串反转后大小写互换位置 public class test_demo { public static void main(String[] args)throws Exception { ...

  7. OpenLDAP 安装及配置 笔记

    首先下载 OpenLdap(Ldap服务器) 和 LdapAdmin(客户端) 两个软件 OpenLDAPforWindows_2.4.39.part1.rar OpenLDAPforWindows_ ...

  8. linux进程状态

    系统维护的时候难免会遇到进程的状态的查询和管理,到底什么是R,有的是S,有的还是S+呢?一直有些混沌的问题,今天细细的来总结一下: ps是用来报告系统中程序执行状况的命令这个是无可厚非的,linux进 ...

  9. Where is "Active Directory Information Extractor"?

    My friend she showed me a screenshot as below yesterday. The name of this document is “EnCase Forens ...

  10. Use EnCase to acquire data from a smartphone

    Yesterday someone asked me a question can EnCase acquire data from a smartphone, and my reply was &q ...