Java NIO SocketChannel
A Java NIO SocketChannel is a channel that is connected to a TCP network socket. It is Java NIO's equivalent of Java Networking's Sockets. There are two ways a SocketChannel can be created:
- You open a SocketChannel and connect to a server somewhere on the internet.
- A SocketChannel can be created when an incoming connection arrives at a
ServerSocketChannel
.
Opening a SocketChannel
Here is how you open a SocketChannel :
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));
Closing a SocketChannel
You close a SocketChannel after use by calling the SocketChannel.close() method. Here is how that is done:
socketChannel.close();
Reading from a SocketChannel
To read data from a SocketChannel you call one of the read() methods. Here is an example:
ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = socketChannel.read(buf);
First a Buffer is allocated. The data read from the SocketChannel is read into the Buffer.
Second the SocketChannel.read() method is called. This method reads data from the SocketChannel into the Buffer. The int returned by the read() method tells how many bytes were witten into the Buffer. If -1 is returned, the end-of-stream is reached (the connection is closed).
Writing to a SocketChannel
Writing data to a SocketChannel is done using the SocketChannel.write() method, which takes a Buffer as parameter. Here is an example:
String newData = "New String to write to file..." + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) {
channel.write(buf);
}
Notice how the SocketChannel .write() method is called inside a while-loop. There is no guarantee of how many bytes the write() method writes to the SocketChannel . Therefore we repeat the write() call until the Buffer has no further bytes to write.
Non-blocking Mode
You can set a SocketChannel into non-blocking mode. When you do so, you can call connect(),read() and write() in asynchronous mode.
connect()
If the SocketChannel is in non-blocking mode, and you call connect(), the method may return before a connection is established. To determine whether the connection is established, you can call the finishConnect() method, like this:
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80)); while(! socketChannel.finishConnect() ){
//wait, or do something else...
}
write()
In non-blocking mode the write() method may return without having written anything. Therefore you need to call the write() method in a loop. But, since this is already being done in the previous write examples, no need to do anything differently here.
read()
In non-blocking mode the read() method may return without having read any data at all. Therefore you need to pay attention to the returned int, which tells how many bytes were read.
Non-blocking Mode with Selectors
The non-blocking mode of SocketChannel's works much better with Selector's. By registering one or more SocketChannel's with a Selector, you can ask the Selector for channels that are ready for reading, writing etc. How to use Selector's with SocketChannel's is explained in more detail in a later text in this tutorial.
Ref:
http://tutorials.jenkov.com/java-nio/socketchannel.html
Java NIO SocketChannel的更多相关文章
- Java NIO SocketChannel套接字通道
原文链接:http://tutorials.jenkov.com/java-nio/socketchannel.html 在Java NIO体系中,SocketChannel是用于TCP网络连接的套接 ...
- Java NIO学习笔记六 SocketChannel 和 ServerSocketChannel
Java NIO SocketChannel Java NIO SocketChannel是连接到TCP网络socket(套接字)的通道.Java NIO相当于Java Networking的sock ...
- Java NIO 完全学习笔记(转)
本篇博客依照 Java NIO Tutorial翻译,算是学习 Java NIO 的一个读书笔记.建议大家可以去阅读原文,相信你肯定会受益良多. 1. Java NIO Tutorial Java N ...
- Java NIO 学习总结 学习手册
原文 并发编程网(翻译):http://ifeve.com/java-nio-all/ 源自 http://tutorials.jenkov.com/java-nio/index.html Java ...
- Java NIO学习系列二:Channel
上文总结了Java NIO中的Buffer相关知识点,本文中我们来总结一下它的好兄弟:Channel.上文有说到,Java NIO中的Buffer一般和Channel配对使用,NIO中的所有IO都起始 ...
- java nio之SocketChannel
Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道.可以通过以下2种方式创建SocketChannel: 打开一个SocketChannel并连接到互联网上的某台服务器. ...
- Java NIO系列教程(八) SocketChannel
Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道.可以通过以下2种方式创建SocketChannel: 打开一个SocketChannel并连接到互联网上的某台服务器. ...
- 源码分析netty服务器创建过程vs java nio服务器创建
1.Java NIO服务端创建 首先,我们通过一个时序图来看下如何创建一个NIO服务端并启动监听,接收多个客户端的连接,进行消息的异步读写. 示例代码(参考文献[2]): import java.io ...
- Java NIO概述
Java NIO 由以下几个核心部分组成: Channels Buffers Selectors 虽然 Java NIO 中除此之外还有很多类和组件,但在我看来,Channel,Buffer 和 Se ...
随机推荐
- Ubuntu系统无法获得锁/var/lib/dpkg/lock - open (11: 资源暂时不可用)的解决方案
Ubuntu系统无法获得锁/var/lib/dpkg/lock - open (11: 资源暂时不可用)的解决方案 问题 使用Ubuntu打开终端时,输入带有sudo apt-get 命令行是 ...
- NOIP练习赛题目1
有些题目可能没做,如计算几何.恶心模拟. 高级打字机 难度级别:C: 运行时间限制:1000ms: 运行空间限制:51200KB: 代码长度限制:2000000B 试题描述 早苗入手了最新的高级打字机 ...
- 工具使用-----Jmeter-脚本的录制
//转载 http://www.cnblogs.com/fnng/archive/2011/08/20/2147082.html 以下是我自己录制的关于这篇文章的视频,有兴趣的可以下载哦 https ...
- Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined) B. Batch Sort 暴力
B. Batch Sort 题目连接: http://codeforces.com/contest/724/problem/B Description output standard output Y ...
- 使用 IntraWeb (6) - 页面模板: TIWLayoutMgrHTML、TIWTemplateProcessorHTML
IW 通过 TIWLayoutMgrHTML 和 TIWTemplateProcessorHTML 使用 HTML 模板. 所谓模板就是一个特殊 HTML 文件, 特殊之处是: 它里面会类似 {% I ...
- CentOS下KVM配置NAT网络(网络地址转换模式)
KVM虚拟机Nat方式上网: # 查看当前活跃的网络 virsh net-list # 查看该网络的详细配置 virsh net-dumpxml default 客户机的XML配置文件中interfa ...
- WCID Devices -- Windows Compatible ID Devices
WCID Devices What is WCID? A WCID device, where WCID stands for "Windows Compatible ID", i ...
- getsockname()/getpeername()函数第一次被调用得到0.0.0.0结果
int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen); getsockname() returns the cu ...
- 利用/proc/pid/pagemap将虚拟地址转换为物理地址
内核文档: Documentation/vm/pagemap.txt pagemap is a new (as of 2.6.25) set of interfaces in the kernel t ...
- MORMOT的数据序列
MORMOT的数据序列 mormot服务器回复客户端通过Ctxt.OutContent属性. 此属性的类型是:SockString. // property OutContent: SockStr ...