Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道。可以通过以下2种方式创建SocketChannel:

打开一个SocketChannel并连接到互联网上的某台服务器。
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress(90));
一个新连接到达ServerSocketChannel时,会创建一个SocketChannel。
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(90));
SocketChannel channel = serverSocketChannel.accept();
关闭 SocketChannel
当用完SocketChannel之后调用SocketChannel.close()关闭SocketChannel:
socketChannel.close();

往SocketChannel中写入数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
buffer.put("测试数据".getBytes("UTF-8"));
buffer.flip();
while(buffer.hasRemaining()){
socketChannel.write(buffer);
}
读取SocketChannel 中的数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = channel.read(buffer);

示例代码
客户端
public class SocketChanneClient {
public static void main(String args[]) throws Exception {
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress(90));
while (true) {
Scanner scanner = new Scanner(System.in);
String message = scanner.next();
sendMessage(channel,message);
}

}

public static void sendMessage(SocketChannel socketChannel, String mes) throws IOException {
if (mes == null || mes.isEmpty()){
return;
}
byte[] bytes = mes.getBytes("UTF-8");
int size = bytes.length;
ByteBuffer buffer = ByteBuffer.allocate(size);
buffer.clear();
buffer.put(bytes);
buffer.flip();
while(buffer.hasRemaining()){
socketChannel.write(buffer);
}
socketChannel.close();

}
}

服务端
public class ServerSocketChannelServer {
public static void main(String[] args) throws IOException{
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(90));
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 10, 1000, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(100));
while (true){
SocketChannel channel = serverSocketChannel.accept();
if ((channel !=null)){
executor.execute( new SocketChannelThread(channel));
}
}
}

}
线程池处理类
public class SocketChannelThread implements Runnable {
private SocketChannel channel;
private String remoteName;

public SocketChannelThread(SocketChannel channel) throws IOException {
this.channel = channel;
this.remoteName = channel.getRemoteAddress().toString();
System.out.println("客户:" + remoteName + " 连接成功!");
}

@Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1024);

byte b[];
while (true) {
try {
b = new byte[1024];
buffer.clear();
int read = channel.read(buffer);
StringBuilder sb = new StringBuilder();
if (read != -1) {
buffer.flip();
int index = 0;
while (buffer.hasRemaining()) {
b[index++] = buffer.get();
if (index >= read) {
index = 0;
sb.append(new String(b, "UTF-8"));
System.out.println(remoteName + ":" + sb.toString());
}
}
buffer.clear();
}

} catch (Exception e) {
System.out.println(remoteName + " 断线了,连接关闭");
try {
channel.close();
} catch (IOException ex) {
}
break;
}
}
}
}

以上创建SocketChannel 是阻塞式的 ,同时也支持非阻塞式的。
阻塞是服务端读取SocketChannel 数据时,如果读取不到,进程一直阻塞直到客户端有数据请求到服务端。
非阻塞是服务端读取SocketChannel 数据时,如果读取不到,java.nio.channels.SocketChannel#read(java.nio.ByteBuffer) 方法返回0
设置非阻塞模式
channel.configureBlocking(false);

NIO学习笔记四 :SocketChannel 和 ServerSocketChannel的更多相关文章

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

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

  2. 零拷贝详解 Java NIO学习笔记四(零拷贝详解)

    转 https://blog.csdn.net/u013096088/article/details/79122671 Java NIO学习笔记四(零拷贝详解) 2018年01月21日 20:20:5 ...

  3. Java NIO学习笔记四 NIO选择器

    Java NIO选择器 A Selector是一个Java NIO组件,可以检查一个或多个NIO通道,并确定哪些通道已准备就绪,例如读取或写入.这样一个线程可以管理多个通道,从而管理多个网络连接. 为 ...

  4. Java NIO 学习笔记(四)----文件通道和网络通道

    目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...

  5. Java NIO学习笔记

    Java NIO学习笔记 一 基本概念 IO 是主存和外部设备 ( 硬盘.终端和网络等 ) 拷贝数据的过程. IO 是操作系统的底层功能实现,底层通过 I/O 指令进行完成. 所有语言运行时系统提供执 ...

  6. Java NIO 学习笔记(三)----Selector

    目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...

  7. Java NIO 学习笔记(一)----概述,Channel/Buffer

    目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...

  8. Java:NIO 学习笔记-3

    Java:NIO 学习笔记-3 根据 黑马程序员 的课程 JAVA通信架构I/O模式,做了相应的笔记 3. JAVA NIO 深入剖析 在讲解利用 NIO 实现通信架构之前,我们需要先来了解一下 NI ...

  9. Java:NIO 学习笔记-1

    Java:NIO 学习笔记-1 说明:本笔记是根据bilibili上 尚硅谷 的课程 NIO视频 而做的笔记 主要内容 Java NIO 简介 Java NIO 与 IO 的主要区别 缓冲区(Buff ...

随机推荐

  1. less的功能和介绍

    在全新的css中,经过程序员们的开发和努力.又打造了全新的less样式表的全新界面,只需引入外部样式表即刻套用,加上了函数定义和取值.大大的降低了代码的书写量.也更加方便程序员的调用和修改!

  2. 关于javac和java

    1.为什么安装完jdk后不配置环境变量就能直接运行java,而不能运行javac 在安装jdk的时候jdk会自带一个jre(java运行环境),还会单独安装一个jre,默认路径是和jdk在同级目录,而 ...

  3. 第二十四节:Java语言基础-讲解数组的综合应用

    数组的综合应用 // 打印数组 public static void printArray(int[] arr) { for(int x=0;x<arr.length;x++) { if(x!= ...

  4. 学爬虫,需要掌握哪些Python基础?

    入手爬虫确实不要求你精通Python编程,但基础知识还是不能忽视的,那么我们需要哪些Python基础呢? 首先我们先来看看一个最简单的爬虫流程:   第一步要确定爬取页面的链接,由于我们通常爬取的内容 ...

  5. Spring Boot定制启动图案

    启动图案 Spring Boot在启动的时候会显示一个默认的Spring的图案,对应的类为SpringBootBanner. . ____ _ __ _ _ /\\ / ___'_ __ _ _(_) ...

  6. [Objective-C语言教程]预处理器(18)

    Objective-C预处理器不是编译器的一部分,而是编译过程中的一个单独步骤. 简单来说,Objective-C预处理器只是一个文本替换工具,它指示编译器在实际编译之前进行必要的预处理. 我们将Ob ...

  7. 浏览器上安装vue devtools

    安装前要检查一下node版本的(node -v),必须将版本提高到>4.4.7.低版本的node在安装devtools时执行npm install 时报错.如何升级node版本,若在window ...

  8. Xamarin.Android 使用 SQLite 出现 Index -1 requested, with a size of 10 异常

    异常: Android.Database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 10 此错误是数据返回 ...

  9. Ubuntu18.04 下修改 root密码

    首先打开终端输入命令 sudo passwd root 然后依次是当前用户密码,将要设置root密码,确认root密码.切换root看一下 备注: #符号 是系统用户 root$符号 是你创建的用户 ...

  10. ES6学习总结

    const只能保证这个指针是固定的,至于它指向的数据结构是不是可变的,就完全不能控制了 const foo = {}; // 为 foo 添加一个属性,可以成功 foo.prop = 123; foo ...