1 SocketChannel

1.1 打开一个SocketChannel

SocketChannel socketChannel = SocketChannel.open();

socketChannel.connect(new InetSocketAddress("http://www.baidu.com", 80));

1.2 关闭一个SocketChannel

socketChannel.close();

1.3 读取一个SocketChannel

ByteBuffer buf = ByteBuffer.allocate(48);

int byteRead = socketChannel.read(buf);

2 ServerSocketChannel

2.1 ServerSocketChannel in blocking mode

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().bind(new InetSocketAddress(1111));

while(true) {

SocketChannel socketChannel = serverSocketChannel.accept();

// do something with socketChannel.......

}

2.2 ServerSocketChannel in non-blocking mode

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().bind(new InetSocketAddress(1111));

serverSocketChannel.configureBlocking(false);

while(true) {

SocketChannel socketChannel = serverSocketChannel.accept();

if (socketChannel != null)

{

// do something with socketChannel.......

}

}

在non-blocking mode时,没有人来connect的时候accept()就会直接返回。这也是non-blocking的意义所在,对于文件而言,总是可以读写的,不存在block一说,也就没有non-blocking mode了。

最新文章

  1. Android 组件属性
  2. mina2线程详解
  3. Android 开机启动
  4. 如何单独启动wamp 中自带的MySQL
  5. JAVA 大数据内存耗用测试
  6. Hibernate3回顾-3-Session管理
  7. .net ADF 中 Ajax 的调用过程.
  8. Bootstrap新手常见问题
  9. 利用innodb_force_recovery修复MySQL数据页损坏
  10. 在Windows下搭建Gitlab服务器
  11. 用git工作的流程
  12. 由AbstractQueuedSynchronizer和ReentrantLock来看模版方法模式
  13. thinkphp的静态缓存,数据缓存,快速缓存,查询缓存
  14. 转:图解C#的值类型,引用类型,栈,堆,ref,out
  15. python 将一个JSON 字典转换为一个Python 对象
  16. devel包
  17. java基础(九) 可变参数列表介绍
  18. 关于spring中<context:component-scan base-package="" />写法
  19. CSS样式呈现优先级
  20. Appcan开发之页面布局与CSS排版(转)

热门文章

  1. 第1节 MapReduce入门:mapreduce的wordcount程序执行问题
  2. 亲测可用)html5 file调用手机摄像头
  3. Servlet中的几个重要的对象(转)
  4. PHP:现有图片验证码类
  5. C++动态申请内存 new T()与new T[]的区别
  6. 第二周习题F
  7. 06-看图理解数据结构与算法系列(AVL树)
  8. Android Studio 使用图片
  9. POJ 1191 DP+DFS棋盘分割问题
  10. 从零开始写STL-容器-list