NIO网络编程中重复触发读(写)事件
一、前言
公司最近要基于Netty构建一个TCP通讯框架, 因Netty是基于NIO的,为了更好的学习和使用Netty,特意去翻了之前记录的NIO的资料,以及重新实现了一遍NIO的网络通讯,不试不知道,一试发现好多细节没注意,导致客户端和服务端通讯的时候出现了一些非常莫名其妙的问题,这边我记录下耗了我一晚上的问题~
二、正文
废话不多说,先上问题代码~
服务端:
package com.nio.server; import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator; public class NIOServer {
private static Selector selector;
private static ServerSocketChannel serverSocketChannel;
private static ByteBuffer bf = ByteBuffer.allocate(1024);
public static void main(String[] args) throws Exception{
init();
while(true){
selector.select();
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey key = it.next();
if(key.isAcceptable()){
System.out.println("连接准备就绪");
ServerSocketChannel server = (ServerSocketChannel)key.channel();
System.out.println("等待客户端连接中........................");
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.register(selector,SelectionKey.OP_READ);
}
else if(key.isReadable()){
System.out.println("读准备就绪,开始读.......................");
SocketChannel channel = (SocketChannel)key.channel();
System.out.println("客户端的数据如下:"); int readLen = 0;
bf.clear();
StringBuffer sb = new StringBuffer();
while((readLen=channel.read(bf))>0){
sb.append(new String(bf.array()));
bf.clear();
}
if(-1==readLen){
channel.close();
}
channel.write(ByteBuffer.wrap(("客户端,你传过来的数据是:"+sb.toString()).getBytes()));
}
it.remove();
}
}
}
private static void init() throws Exception{
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(8080));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
}
客户端:
package com.nio.client; import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator; public class NIOClient {
private static Selector selector;
public static void main(String[]args) throws Exception{
selector = Selector.open();
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("127.0.0.1",8080));
sc.register(selector,SelectionKey.OP_READ); ByteBuffer bf = ByteBuffer.allocate(1024);
bf.put("Hi,server,i'm client".getBytes()); if(sc.finishConnect()){
bf.flip();
while(bf.hasRemaining()){
sc.write(bf);
} while(true){
selector.select();
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey key = it.next(); if(key.isReadable()){
bf.clear();
SocketChannel othersc = (SocketChannel)key.channel();
othersc.read(bf);
System.out.println("服务端返回的数据:"+new String(bf.array()));
}
}
selector.selectedKeys().clear();
}
}
}
}
服务端运行结果:
客户端运行结果:
这边我们可以看到,客户端输出了两次,笔者调试的时候发现,服务端只往客户端写过一次数据,但是客户端却打印了两次数据,而且两次的数据不一样,挺诡异的!然后我就各种查,折磨了我一夜,今早一来,又想着怎么解决问题,不经意间发现了一篇文章:java nio使用的是水平触发还是边缘触发?,文章中指出Nio的Selector.select()是“水平触发”(也叫“条件触发”),只要条件一直满足,那么就会一直触发,至此我如醍醐灌顶:是不是我通道里面的数据第一次没有读取干净?导致客户端触发了多次读取?后来验证之后,发现确实是这个问题,读者可以看我服务器端的代码,我返回的是数据字节数是:"服务端返回的数据:".length()+bf.array().length=26+1024,而客户端只是将这个数据读入1024大小的ByteBuffer中,还有26字节没有读取干净,所以就触发了第二次的读事件!!!
既然问题找到了,现在就是要解决如何将通道内的数据读取干净了,修改之后的代码如下, 特别注意红色部分:
服务端:
package com.nio.server; import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator; public class NIOServer {
private static Selector selector;
private static ServerSocketChannel serverSocketChannel;
private static ByteBuffer bf = ByteBuffer.allocate(1024);
public static void main(String[] args) throws Exception{
init();
while(true){
selector.select();
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey key = it.next();
if(key.isAcceptable()){
System.out.println("连接准备就绪");
ServerSocketChannel server = (ServerSocketChannel)key.channel();
System.out.println("等待客户端连接中........................");
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.register(selector,SelectionKey.OP_READ);
}
else if(key.isReadable()){
System.out.println("读准备就绪,开始读.......................");
SocketChannel channel = (SocketChannel)key.channel();
System.out.println("客户端的数据如下:"); int readLen = 0;
bf.clear();
StringBuffer sb = new StringBuffer();
while((readLen=channel.read(bf))>0){
bf.flip();
byte [] temp = new byte[readLen];
bf.get(temp,0,readLen);
sb.append(new String(temp));
bf.clear();
}
if(-1==readLen){
channel.close();
}
System.out.println(sb.toString());
channel.write(ByteBuffer.wrap(("客户端,你传过来的数据是:"+sb.toString()).getBytes()));
}
it.remove();
}
}
}
private static void init() throws Exception{
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(8080));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
}
客户端:
package com.nio.client; import java.io.ByteArrayOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator; public class NIOClient {
private static Selector selector;
public static void main(String[]args) throws Exception{
selector = Selector.open();
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("127.0.0.1",8080));
sc.register(selector,SelectionKey.OP_READ); ByteBuffer bf = ByteBuffer.allocate(1024);
bf.put("Hi,server,i'm client".getBytes()); if(sc.finishConnect()){
bf.flip();
while(bf.hasRemaining()){
sc.write(bf);
} while(true){
selector.select();
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey key = it.next(); if(key.isReadable()){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bf.clear();
SocketChannel othersc = (SocketChannel)key.channel();
while(othersc.read(bf)>0){
bf.flip();
while(bf.hasRemaining()){
bos.write(bf.get());
}
bf.clear();
};
System.out.println("服务端返回的数据:"+bos.toString());
}
}
selector.selectedKeys().clear();
}
}
}
}
客户端的输出:
三、参考链接
https://www.zhihu.com/question/22524908
四、联系本人
为方便没有博客园账号的读者交流,特意建立一个企鹅群(纯公益,非利益相关),读者如果有对博文不明之处,欢迎加群交流:261746360,小杜比亚-博客园。
NIO网络编程中重复触发读(写)事件的更多相关文章
- Netty | 第1章 Java NIO 网络编程《Netty In Action》
目录 前言 1. Java 网络编程 1.1 Javs NIO 基本介绍 1.2 缓冲区 Buffer 1.2 通道 Channel 1.3 选择器 Selector 1.4 NIO 非阻塞网络编程原 ...
- 浅谈TCP/IP网络编程中socket的行为
我认为,想要熟练掌握Linux下的TCP/IP网络编程,至少有三个层面的知识需要熟悉: 1. TCP/IP协议(如连接的建立和终止.重传和确认.滑动窗口和拥塞控制等等) 2. Socket I/O系统 ...
- 【Linux网络编程】TCP网络编程中connect()、listen()和accept()三者之间的关系
[Linux网络编程]TCP网络编程中connect().listen()和accept()三者之间的关系 基于 TCP 的网络编程开发分为服务器端和客户端两部分,常见的核心步骤和流程如下: conn ...
- 网络编程中select模型和poll模型学习(linux)
一.概述 并发的网络编程中不管是阻塞式IO还是非阻塞式IO,都不能很好的解决同时处理多个socket的问题.操作系统提供了复用IO模型:select和poll,帮助我们解决了这个问题.这两个函数都能够 ...
- Java网络编程中异步编程的理解
目录 前言 一.异步,同步,阻塞和非阻塞的理解 二.异步编程从用户层面和框架层面不同角度的理解 用户角度的理解 框架角度的理解 三.为什么使用异步 四.理解这些能在实际中的应用 六.困惑 参考文章 前 ...
- [转帖]关于网络编程中MTU、TCP、UDP优化配置的一些总结
关于网络编程中MTU.TCP.UDP优化配置的一些总结 https://www.cnblogs.com/maowang1991/archive/2013/04/15/3022955.html 感谢原作 ...
- java 基础之--nio 网络编程
在传统的Java 网络编程中,对于客户端的每次连接,对于服务器来说,都要创建一个新的线程与客户端进行通讯,这种频繁的线程的创建,对于服务器来说,是一种巨大的损耗,在Java 1.4 引入Java ni ...
- 网络编程中的read,write函数
关于TCP/IP协议,建议参考Richard Stevens的<TCP/IP Illustrated,vol1>(TCP/IP详解卷1). 关于第二层面,依然建议Richard Steve ...
- Unix网络编程中的五种I/O模型_转
转自:Unix网络编程中的的五种I/O模型 下面主要是把unp第六章介绍的五种I/O模型. 1. 阻塞I/O模型 例如UDP函数recvfrom的内核到应用层.应用层到内核的调用过程是这样的:首先把描 ...
随机推荐
- 5.18-笨办法学python-习题16(write)
from sys import argv script,filename=argv #固定模式啦 print("we're going to erase %r."%filename ...
- Matlab_GUI
1.GUI中控件的属性 BackgroundColor 控件的背景 FontSize 控件字体的大小
- 补交 20155202 蓝墨云班课 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能
蓝墨云班课 编写MyCP.java 要求: 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能,要求MyCP支持两个参数: java MyCP -tx XXX1.txt XXX ...
- linux编程实践:实现pwd命令
内核为每个目录都设置了一个指向自己的i节点入口,即".",还有一个指向其父目录i节点的入口,即"..",我们首先获取当前目录的i节点编号,但是并不能知道当前目录 ...
- 20155328 2016-2017-2 《Java程序设计》 第十周学习内容总结
20155328 2016-2017-2 <Java程序设计>第十周学习总结 教材学习内容总结 JAVA和ANDROID开发学习指南 第22章 网络概览 两台计算机用于通信的语言叫做&qu ...
- BZOJ4034_树上操作_KEY
题目传送门 这道题可以树链剖分+线段树. 其他操作模板,第二个操作只需要将x~x+size[x]-1区间加值即可. code: #include <cstdio> #include < ...
- 3-3 修改haproxy配置文件
1.需求 2.个人思路 3.个人心得 4.
- Azkaban 工作流调度器
Azkaban 工作流调度器 1 概述 1.1 为什么需要工作流调度系统 a)一个完整的数据分析系统通常都是由大量任务单元组成,shell脚本程序,java程序,mapreduce程序.hive脚本等 ...
- mac php版本切换
mac os 中自带php版本,但是很多扩展是不带的. 这个网站: http://php-osx.liip.ch/提供了几乎所有的php版本 通过输入 curl -s http://php-osx.l ...
- 译图智讯VIN码识别助力汽配商转型升级
汽配猫是上海佳驰经合能源科技有限公司自主开发的汽车配件B2B网上商城及服务平台,该平台依托互联网云技术.利用创新的商业模式及互联网思维,整合汽配产业链优秀资源,为汽车维修保养企业等产业链各方面提供汽配 ...