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:

  1. You open a SocketChannel  and connect to a server somewhere on the internet.
  2. 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的更多相关文章

  1. Java NIO SocketChannel套接字通道

    原文链接:http://tutorials.jenkov.com/java-nio/socketchannel.html 在Java NIO体系中,SocketChannel是用于TCP网络连接的套接 ...

  2. Java NIO学习笔记六 SocketChannel 和 ServerSocketChannel

    Java NIO SocketChannel Java NIO SocketChannel是连接到TCP网络socket(套接字)的通道.Java NIO相当于Java Networking的sock ...

  3. Java NIO 完全学习笔记(转)

    本篇博客依照 Java NIO Tutorial翻译,算是学习 Java NIO 的一个读书笔记.建议大家可以去阅读原文,相信你肯定会受益良多. 1. Java NIO Tutorial Java N ...

  4. Java NIO 学习总结 学习手册

    原文 并发编程网(翻译):http://ifeve.com/java-nio-all/  源自 http://tutorials.jenkov.com/java-nio/index.html Java ...

  5. Java NIO学习系列二:Channel

    上文总结了Java NIO中的Buffer相关知识点,本文中我们来总结一下它的好兄弟:Channel.上文有说到,Java NIO中的Buffer一般和Channel配对使用,NIO中的所有IO都起始 ...

  6. java nio之SocketChannel

    Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道.可以通过以下2种方式创建SocketChannel: 打开一个SocketChannel并连接到互联网上的某台服务器. ...

  7. Java NIO系列教程(八) SocketChannel

    Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道.可以通过以下2种方式创建SocketChannel: 打开一个SocketChannel并连接到互联网上的某台服务器. ...

  8. 源码分析netty服务器创建过程vs java nio服务器创建

    1.Java NIO服务端创建 首先,我们通过一个时序图来看下如何创建一个NIO服务端并启动监听,接收多个客户端的连接,进行消息的异步读写. 示例代码(参考文献[2]): import java.io ...

  9. Java NIO概述

    Java NIO 由以下几个核心部分组成: Channels Buffers Selectors 虽然 Java NIO 中除此之外还有很多类和组件,但在我看来,Channel,Buffer 和 Se ...

随机推荐

  1. valgrind 内存调试工具

    一.valgrind 是运行在linux系统下的内存调试工具,支持很多对象:memcheck.addrcheck.cachegrind.Massif.helgrind.Callgrind等.使用val ...

  2. 高能天气——团队Scrum冲刺阶段-Day 3

    高能天气--团队Scrum冲刺阶段-Day 3 今日完成任务 于欣月:完成天气预报部分收尾工作 余坤澎:进行特别关心的实现 康皓越:实现闹钟部分添加音乐 范雯琪:初步开始界面优化,寻找天气预报部分的背 ...

  3. 决策树ID3算法--python实现

    参考: 统计学习方法>第五章决策树]   http://pan.baidu.com/s/1hrTscza 决策树的python实现     有完整程序     决策树(ID3.C4.5.CART ...

  4. 系统的Drawable(四)-LayerListDrawable

    系统的Drawable(四)-LayerListDrawable 学习自 https://blog.csdn.net/u014695188/article/details/52815444 Layer ...

  5. python的异常处理及异常类定义

    python的异常处理语法和大多数语言相似: try: try块的语句... except exceptiontype1 as var:#使用as语句获得本次捕获到的异常的实例var except块语 ...

  6. bzoj 3673 可持久化并查集

    本质上是维护两个可持久化数组,用可持久化线段树维护. /************************************************************** Problem: ...

  7. UVALive 6915 Leveling Ground 倍增RMQ

    Leveling Ground 题目连接: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid ...

  8. AtomicReference,AtomicStampedReference与AtomicMarkableReference的区别

    AtomicReference 通过volatile和Unsafe提供的CAS函数实现原子操作. 自旋+CAS的无锁操作保证共享变量的线程安全 value是volatile类型,这保证了:当某线程修改 ...

  9. MikroTik RouterOS安装chr授权到阿里云虚拟机(转)

    CHR介绍 CHR(Cloud Hosted Router) 是用于在虚拟机上运行的 RouterOS 版本,它支持x86_64架构,支持大多数流行的虚拟化技术,如 VMWare, Hyper-V, ...

  10. 国内代码托管git-osc基础使用教程

    git-osc是开源中国社区团队推出的基于Git的快速的.免费的.稳定的在线代码托管平台,不限制私有库和公有库数量.国内同类的有taocode.SVNchina等等 个人更喜欢git-osc的界面与操 ...