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 ...
随机推荐
- 常用工具(Windows版本)
为原有版本修改为markdown后的更新,这个编辑器真心不错,只需要把原来喜欢的表格改成列表即可. 代码工具 代码管理工具 SourceTree:支持windows和mac跨平台使用的git图形化客户 ...
- JDBC之 大数据内容的传输
JDBC之 大数据内容的传输 什么是大数据内容? 在数据库中,有一条一条的记录,记录中很多字段都是几个字符就够的,假如现在要把一部小说存入数据库,这本小说当然不是几个字符组成,而是由几万字组成,这本小 ...
- faker php测试数据库生成
官方地址:https://github.com/fzaninotto/Faker 使用方式: 1.composer直接下载: composer require fzaninotto/faker 2.将 ...
- usb3.0 monitor is already started
用360 开机加速里找到这个程序,把它从开机启动中删除掉就好.
- 【BZOJ-1493】项链工厂 Splay
1493: [NOI2007]项链工厂 Time Limit: 30 Sec Memory Limit: 64 MBSubmit: 1440 Solved: 626[Submit][Status] ...
- 【原】Spring整合Redis(第三篇)—盘点SDR搭建中易出现的错误
易错点01:Spring版本过低导致的错误[环境参数]Redis版本:redis-2.4.5-win32-win64Spring原来的版本:4.1.7.RELEASESpring修改后的版本:4.2. ...
- oracle直接读写ms sqlserver数据库(二)配置透明网关
环境说明: 数据库版本:11gR2 透明网关版本:11g 操作系统Windows Server2008_64位 ORACLE_HOME目录:D:\app\Administrator\product\1 ...
- Redis使用小结
Redis官方没有windows版本的,对于Windows环境的redis,有如下两个方案 微软的移植版本,但只支持到3.2 下载地址 win10及以上的版本直接通过win10的liunx子系统执行 ...
- jPlayer插件的使用
文讲一下本人在使用jPlayer插件时的整个过程.出现的BUG已经解决办法. 最近在做bootstrap项目,项目中需要一个响应式.兼容IE7的视频播放插件,经过上网查找,找到了所谓可以兼容到IE6的 ...
- GoDaddy Linux主机支持机房的更换
GoDaddy Linux主机支持机房的更换 http://godaddy.idcspy.com/godaddy-change-data-center GoDaddy推出中文界面后,小编发现虚拟主机有 ...