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