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. Android SDK platforms build-tools等镜像下载

    Android SDK platforms build-tools等镜像下载     下载地址:http://mirrors.neusoft.edu.cn/android/repository/  这 ...

  2. EDMA3 笔记

          A-synchronized和AB-synchronized传输在1个frame传输完成后地址计算有所不同. A-synchronized: last array in the frame ...

  3. asp.net core 中的SignalR与web前端进行实时通信

    一.介绍 SignalR是.net 开源库,用于构建需要实时进行用户交互和数据更新的web应用,如在线聊天,游戏,天气等实时应用程序,且简化了构建实时应用的过程,包括服务端库和js端库,继承了数种常见 ...

  4. 1200 同余方程 2012年NOIP全国联赛提高组

    题目描述 Description 求关于 x 同余方程 ax ≡ 1 (mod b)的最小正整数解. 输入描述 Input Description 输入只有一行,包含两个正整数 a, b,用 一个 空 ...

  5. hdu 4432 第37届ACM/ICPC天津现场赛B题

    题目大意就是找出n的约数,然后把约数在m进制下展开,各个数位的每一位平方求和,然后按m进制输出. 模拟即可 #include<cstdio> #include<iostream> ...

  6. bzoj 2648: SJY摆棋子&&2716: [Violet 3]天使玩偶 --kdtree

    2648: SJY摆棋子&&2716: [Violet 3]天使玩偶 Time Limit: 20 Sec  Memory Limit: 128 MB Description 这天,S ...

  7. hdu 5775 Bubble Sort 树状数组

    Bubble Sort 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5775 Description P is a permutation of t ...

  8. Xcode6 iOS7模拟器和Xcode7 iOS8模拟器离线下载

    Xcode6 只支持iOS7和iOS8的模拟器 Xcode7 只支持iOS9和iOS8的模拟器 Xcode 并不会识别 SDKs 目录下的模拟器,我经过一些尝试以后,发现要放在这个目录下: /Libr ...

  9. 解决Android LogCat 输出乱码的问题(转)

    Android日志系统提供了记录和查看系统调试信息的功能.日志都是从各种软件和一些系统的缓冲区中记录下来的. 可以使用adb的logcat 命令来查看系统日志缓冲区的内容,但是在实际操作时,会发现在C ...

  10. Serilog简介

    Serilog是.net 下的新兴的日志框架,本文这里简单的介绍一下它的用法. 首先安装Nuget包: Install-Package Serilog Install-Package Serilog. ...