NIO 编程示例代码

server

 

package nio;

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;

public class Server implements Runnable {
	// The port we will listen on
	private int port;

	// A pre-allocated buffer for encrypting data
	private final ByteBuffer buffer = ByteBuffer.allocate(16384);

	public Server(int port) {
		this.port = port;
		new Thread(this).start();
	}

	public void run() {
		try {
			// Instead of creating a ServerSocket,
			// create a ServerSocketChannel
			ServerSocketChannel ssc = ServerSocketChannel.open();

			// Set it to non-blocking, so we can use select
			ssc.configureBlocking(false);

			// Get the Socket connected to this channel, and bind it
			// to the listening port
			ServerSocket ss = ssc.socket();
			InetSocketAddress isa = new InetSocketAddress(port);
			ss.bind(isa);

			// Create a new Selector for selecting
			Selector selector = Selector.open();

			// Register the ServerSocketChannel, so we can
			// listen for incoming connections
			ssc.register(selector, SelectionKey.OP_ACCEPT);
			System.out.println("Listening on port " + port);

			while (true) {
				// See if we've had any activity -- either
				// an incoming connection, or incoming data on an
				// existing connection
				int num = selector.select();

				// If we don't have any activity, loop around and wait
				// again
				if (num == 0) {
					continue;
				}

				// Get the keys corresponding to the activity
				// that has been detected, and process them
				// one by one
				Set keys = selector.selectedKeys();
				Iterator it = keys.iterator();
				while (it.hasNext()) {
					// Get a key representing one of bits of I/O
					// activity
					SelectionKey key = (SelectionKey) it.next();

					// What kind of activity is it?
					if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

						System.out.println("acc");
						// It's an incoming connection.
						// Register this socket with the Selector
						// so we can listen for input on it

						Socket s = ss.accept();
						System.out.println("Got connection from " + s);

						// Make sure to make it non-blocking, so we can
						// use a selector on it.
						SocketChannel sc = s.getChannel();
						sc.configureBlocking(false);

						// Register it with the selector, for reading
						sc.register(selector, SelectionKey.OP_READ);
					} else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

						SocketChannel sc = null;

						try {

							// It's incoming data on a connection, so
							// process it
							sc = (SocketChannel) key.channel();
							boolean ok = processInput(sc);

							// If the connection is dead, then remove it
							// from the selector and close it
							if (!ok) {
								key.cancel();

								Socket s = null;
								try {
									s = sc.socket();
									s.close();
								} catch (IOException ie) {
									System.err.println("Error closing socket "
											+ s + ": " + ie);
								}
							}

						} catch (IOException ie) {

							// On exception, remove this channel from the
							// selector
							key.cancel();

							try {
								sc.close();
							} catch (IOException ie2) {
								System.out.println(ie2);
							}

							System.out.println("Closed " + sc);
						}
					}
				}

				// We remove the selected keys, because we've dealt
				// with them.
				keys.clear();
			}
		} catch (IOException ie) {
			System.err.println(ie);
		}
	}

	// Do some cheesy encryption on the incoming data,
	// and send it back out
	private boolean processInput(SocketChannel sc) throws IOException {
		buffer.clear();
		sc.read(buffer);
		buffer.flip();

		// If no data, close the connection
		if (buffer.limit() == 0) {
			return false;
		}

		// Simple rot-13 encryption
		for (int i = 0; i < buffer.limit(); ++i) {
			byte b = buffer.get(i);

			if ((b >= 'a' && b <= 'm') || (b >= 'A' && b <= 'M')) {
				b += 13;
			} else if ((b >= 'n' && b <= 'z') || (b >= 'N' && b <= 'Z')) {
				b -= 13;
			}

			buffer.put(i, b);
		}

		sc.write(buffer);

		System.out.println("Processed " + buffer.limit() + " from " + sc);

		return true;
	}

	static public void main(String args[]) throws Exception {
		int port = Integer.parseInt(args[0]);

		new Server(port);
	}
}

 

client NIO方式实现

/**
 * 
 */
package com.topsci.xxxxxx.provider.service;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
class TestClient {
	private static Logger logger = LoggerFactory.getLogger(TestClient.class);//slf4j logging

	// The host:port combination to connect to
    private InetAddress hostAddress;
    private int         port;
    private SocketChannel client;
    
    protected Charset charset = Charset.forName("UTF-8");  
	protected CharsetEncoder charsetEncoder = charset.newEncoder();  
	protected CharsetDecoder charsetDecoder = charset.newDecoder(); 
    
    public TestClient(InetAddress hostAddress, int port) throws IOException{
		this.hostAddress = hostAddress;
		this.port = port;
		
		// Create a non-blocking socket channel
        client = SocketChannel.open();
//        client.configureBlocking(false);
//        client.register(this.selector, SelectionKey.OP_CONNECT);

        // Kick off connection establishment
        client.connect(new InetSocketAddress(this.hostAddress, this.port));
	}
    
    private void request(String msg){
		ByteBuffer buffer = ByteBuffer.allocate(100);
		try {
			this.client.write(charsetEncoder.encode(CharBuffer.wrap(msg)));
			int len = this.client.read(buffer);
			if (len > 0){
				buffer.flip();
				logger.info(charsetDecoder.decode(buffer).toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
	
	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		// TODO Auto-generated method stub
		TestClient client = new TestClient(InetAddress.getByName("localhost"), 9999);
		Random random = new Random();
		
		for (int i = 5; i > 0; i--){
			String req = "请求编号 " + random.nextInt();
			client.request(req);
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
 

 

client 传统方式实现

 

package nio;

import java.io.*;
import java.net.*;
import java.util.*;

public class Client implements Runnable {
	private String host;
	private int port;

	// Bounds on how much we write per cycle
	private static final int minWriteSize = 1024;
	private static final int maxWriteSize = 65536;

	// Bounds on how long we wait between cycles
	private static final int minPause = (int) (0.05 * 1000);
	private static final int maxPause = (int) (0.5 * 1000);

	// Random number generator
	Random rand = new Random();

	public Client(String host, int port, int numThreads) {
		this.host = host;
		this.port = port;

		for (int i = 0; i < numThreads; ++i) {
			new Thread(this).start();
		}
	}

	public void run() {

		byte buffer[] = new byte[maxWriteSize];

		try {
			Socket s = new Socket(host, port);

			InputStream in = s.getInputStream();
			OutputStream out = s.getOutputStream();

			while (true) {
				int numToWrite = minWriteSize
						+ (int) (rand.nextDouble() * (maxWriteSize - minWriteSize));

				for (int i = 0; i < numToWrite; ++i) {
					buffer[i] = (byte) rand.nextInt(256);
				}

				out.write(buffer, 0, numToWrite);
				int sofar = 0;
				while (sofar < numToWrite) {
					sofar += in.read(buffer, sofar, numToWrite - sofar);
				}

				System.out.println(Thread.currentThread() + " wrote "
						+ numToWrite);

				int pause = minPause
						+ (int) (rand.nextDouble() * (maxPause - minPause));
				try {
					Thread.sleep(pause);
				} catch (InterruptedException ie) {
				}
			}
		} catch (IOException ie) {
			ie.printStackTrace();
		}
	}

	static public void main(String args[]) throws Exception {
		String host = args[0];
		int port = Integer.parseInt(args[1]);
		int numThreads = Integer.parseInt(args[2]);

		new Client(host, port, numThreads);
	}
}
基于NIO的Socket通信(使用Java NIO的综合示例讲解) 本篇文章并不是NIO和Socket的入门文章,如果你在看完后有些难度可以先学习基础知识后再进行阅读,但是本文的一些概念不论是入门还是学习已久的人都会有些许收获。(感觉基础不足的可以阅读前文两个链接来获取更多的细节) 一、NIO的简介 Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,Java NIO提供了与标准IO不同的IO工作方式: IO NIO... 阅读详情

相关推荐

Java NIO 编程的代码示例与解释

Java NIO(New Input/Output)是Java 1.4引入的一套全新的IO API,旨在提供更高效的IO操作能力。本文旨在全面介绍Java NIO编程的核心概念,通过实际代码示例展示其使用方法,并深入分析其底层实现原理。文章首先介绍NIO的核心概念,然后深入分析其三大组件,接着通过实际代码示例展示NIO编程,最后讨论应用场景和性能优化技巧。:Java提供的新IO API,支持非阻塞和选择器驱动的IO操作Channel(通道):代表与实体的连接,如文件、套接字等Buffer(缓冲区)

AI开发架构师 860

NIO 简单实例

前言 在 Java 中,数据传输 IO 模型大概分为三类:BIO(同步阻塞)、NIO(同步非阻塞)、AIO(异步非阻塞)。 在 BIO 中,服务器会针对每一个连接都去开一个新的线程进行处理,这样实现非常简单快速,但是对于资源消耗巨大,于是提出了 NIO。 在看本博客之前建议先了解一下 NIO 的基本用法。 一、NIO简介 NIO 是一种基于事件驱动的 IO 模型,面向缓冲区编程,NIO有三大核心部分:Channel(通道)、Buffer(缓冲区)、Selector(选择器)。通俗理解,NIO 的一个线程管理

淦淦淦! 1835

Java NIO非阻塞IO编程实战示例代码集

字段长度说明40xCAFEBABEType11=文本, 2=文件, 3=心跳Length4数据体长度Data变长实际内容编码逻辑:解码需处理粘包拆包:if (magic!Java NIO 不仅仅是为了“更快”,更是为了更可控、更灵活、更具扩展性的系统设计。它教会我们:- 如何用少量线程支撑海量连接- 如何精细控制内存布局。

weixin_42402664的博客 429

Java基础(三) NIO网络编程

NIO全称为 Non-Blocking IO 即非阻塞式IO,也是I/O多路复用的基础,已经被越来越多地应用到大型应用服务器,成为解决高并发与大量连接、I/O处理问题的有效方式。传统IO数据传输与NIO的区别如下...

这里是阿安的博客 754

JAVA-NIO程序设计完整实例

NULL 博文链接:https://shift-alt-ctrl.iteye.com/blog/1840554

Java高并发编程代码(Netty NIO 实例)

Java高并发编程代码(Netty NIO 实例)

NIO入门实例-写一个客户端/服务器例程

注:该文章实际为《java网络编程》例11-1和例11-2的源码勘误!原例程经过实际测试并不能实现期望的功能,在分析代码逻辑后勘误如下! 在勘误之前贴出书中原始例程(仅服务器有误): package org.nioTest; import sun.rmi.runtime.Log; import java.io.IOException; import java.net.InetSocke...

站在人文与技术的交汇点 620

深入解析.Net中SM2与sm-crypto的跨平台加解密实践

本文深入探讨了在.Net平台与前端sm-crypto库之间实现SM2国密算法跨平台加解密的实践方案。针对对接中常见的密钥格式、密文拼接顺序(C1C3C2与C1C2C3)等核心难点,提供了基于BouncyCastle的完整工具类实现、前后端联调示例及问题排查指南,旨在帮助开发者构建安全、兼容的数据加密通道。

weixin_29322855的博客 369

java read 没有读到tcp数据 tcpdump显示数据已在缓冲区_Java性能优化之使用NIO提升性能...

前言在软件系统中,由于IO的速度要比内存慢,因此,I/O读写在很多场合都会成为系统的瓶颈。提升I/O速度,对提升系统整体性能有着很大的好处。在Java的标准I/O中,提供了基于流的I/O实现,即InputStream和OutputStream。这种基于流的实现以字节为单位处理数据,并且非常容易建立各种过滤器。NIO是New I/O的简称,具有以下特性:为所有的原始类型提供(Buffer)缓存支持;...

weixin_39880615的博客 361

关于Win11安装Ubuntu子系统报错:WslRegisterDistribution failed with error 解决办法

Win11安装Ubuntu子系统报错:WslRegisterDistribution failed with error

qq_51908382的博客 3万+

python电子学会三级的零碎笔记

‌示例‌:如果s = ['a', 'b', 'c'],则' '.join(s)+'\n'的结果是'a b c\n',写入文件时所有元素会在一行内显示,每个元素之间用空格分隔,末尾有一个换行符。(2) '\n'.join(s)‌:如果s = ['a', 'b', 'c'],则'\n'.join(s)的结果是'a\nb\nc',写入文件时每个元素会占据文件的一行。(1) ' '.join(s)+'\n'‌:这种方式首先将列表s中的每个元素通过空格连接成一个字符串,然后在字符串末尾添加一个换行符\n。

xzal12的博客 690

Java NIO 模型代码示例

在高并发(持续大量的连接同时请求)场景中,之前的两种 BIO 优化方案都需要消耗大量的线程来维持连接。并且 CPU 在线程切换上消耗很大。 Java NIO 模型的主要优势:少量的线程就可以处理大量连接的请求。 主要组成: Channel 通道:IO 传输发生时数据通过的入口 Buffer 缓冲区:可以理解为数据在管道传输时的起点和终点 Selector 选取器(IO监听器):负责监听 IO 事件 所用通道都向 Selector 注册,Selector 负责轮询检测,然后服务端进程会阻塞在 Select

qq_33471737的博客 2113

手把手教你用Simulink搭建交流异步电机矢量控制模型(附完整仿真文件)

本文提供了一份详细的Simulink仿真指南,手把手教你从零开始搭建交流异步电机矢量控制模型。内容涵盖主电路搭建、坐标变换实现、双闭环PI调节器设计、转子磁链观测器调试等核心步骤,并附有完整的仿真文件,帮助读者跨越理论到实践的鸿沟,掌握高性能电机控制系统的建模与仿真技能。

pz890123的博客 665

BIO,Socket网络编程入门代码示例,NIO网络编程入门代码示例,AIO 网络编程

                             BIO,Socket网络编程入门代码示例 1.BIO服务器端程序 package cn.itcast.bio; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; ...

苏凯的博客 370

深入Scrapy ItemLoader:打造优雅高效的Python爬虫数据清洗流水线

ItemLoader是 Scrapy 提供的声明式数据加载工具。它的核心理念是:将数据提取(从response中取原始值)和数据清洗/验证(处理空值、格式转换、默认值等)分离开。你可以把它想象成一个工厂流水线:原始零件(selector提取的文本)进入,经过一道道工序(输入处理器),组装成最终产品(Item字段)。首先在items.py中定义清晰的数据结构。使用搭配类型注释(虽然Scrapy自身不强制,但对人和IDE友好)。

2201_76125261的博客 68

【x265编码器】章节1——x265的lookahead模块分析

目录一、模块功能二、lookahead模块分析1.调用流程2.代码分析Lookahead::addPicture()Lookahead::checkLookaheadQueue()Lookahead::getDecidedPicture()Lookahead::findJob()Lookahead::slicetypeDecide()PreLookaheadGroup::processTasksLookaheadTLD::lowresIntraEstimate()Lookahead::slicetypeAn

vcvdv123的博客 4万+

超硬核!!!一篇文章搞定BIO、NIO、AIO、Netty(详细基础内容+网络编程内容+代码示例)【网络编程 2】

BIO、NIO、AIO、NettyBIO、NIO、AIO、Netty什么是IO在了解不同的IO之前先了解:同步与异步,阻塞与非阻塞的区别什么是BIO什么是NIO什么是AIO什么NettyBIO和NIO、AIO的区别IO流的分类什么是内核空间五种IO模型1.阻塞IO(blocking I/O)2.非阻塞IO(noblocking I/O)3.异步IO(asynchronous I/O)4.信号驱动I...

小杰爱吃蛋的博客 1万+

如何用 Claude Code 做代码重构,而不是重写

摘要: 在使用Claude Code进行代码优化时,AI容易“重写”而非“重构”,导致改动过大、review困难。本文提出3个关键约束方法:1)限制修改范围(如仅修改指定函数);2)明确不改变代码行为;3)要求最小必要修改。通过分步骤重构、先获取重构建议再修改、使用标准模板(保持函数签名/输入输出/结构不变)等方式,可使AI输出更符合工程需求的小范围安全重构。对于彻底混乱的代码,才建议直接重写。核心在于通过提示词精准约束AI的修改行为,将其转化为高效的代码重构助手。

sg_knight的专栏 980

Netty——网络编程 NIO(Selector处理read事件)代码示例

Netty——NIO(Selector处理read事件)代码示例

小志的博客 850

SpringCloud Alibaba - Seata 实现高可用和异地容灾

这里不仅仅要实现高可用,还需要实现异地容灾. 异地容灾就是说,如果你整了好几个节点部署起来,全部放到一个机房里面,那么如果这个机房出了故障,就意味着整个集群就完了,所以对于一个大型的集群来讲,都会把这些服务异地部署.问题2:如果我们要实现异地容灾,也就说某一个机房挂了,需要快速的切换到另一个可用的机房,但是这个配置在配置文件中写死了,如果要改配置文件,还需要重启服务器,这是我们不希望看到的,怎么办?进入 seata/bin 目录,运行 seata-server.bat 文件,默认端口为 8091。

CYK_byte的博客 975

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Netty——网络编程 NIO(Selector处理accept事件)代码示例

Netty——网络编程 NIO(Selector处理accept事件)代码示例

小志的博客 737

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Netty——网络编程 NIO(Selector处理write事件 写入内容过多问题)代码示例

Netty——网络编程 NIO(Selector处理write事件 写入内容过多问题)代码示例

小志的博客 671

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

超硬核!!!一篇文章搞定BIO、NIO、AIO、Netty(详细基础内容+网络编程内容+代码示例)

BIO、NIO、AIO、NettyBIO、NIO、AIO、Netty什么是IO在了解不同的IO之前先了解:同步与异步,阻塞与非阻塞的区别什么是BIO什么是NIO什么是AIO什么NettyBIO和NIO、AIO的区别IO流的分类什么是内核空间五种IO模型1.阻塞IO(blocking I/O)2.非阻塞IO(noblocking I/O)3.异步IO(asynchronous I/O)4.信号驱动I...

小杰爱吃蛋的博客 2348

Netty——网络编程 NIO(Selector处理read事件 客户端断开问题解决)代码示例

Netty——网络编程 NIO(Selector处理read事件 客户端断开问题解决)代码示例

小志的博客 1762

java nio socket 例子_Java NIO socket编程实例

晚上学习了下Java 的 NIO Socket编程,写了下面这个小程序,包括服务器端与客户端。实现的功能为客户端向服务器端发送随即数目的消息,服务器端一条一条的回应。消息内容保存在talks.properties文件中,内容为:Hi=HiBye=Bye床前明月光=疑是地上霜举头望明月=低头思故乡少小离家老大回=乡音无改鬓毛衰天王盖地虎=宝塔镇河妖我是甲=我是乙我是客户端=我是服务器我是周星驰=我是...

weixin_32153867的博客 350

超硬核!!!一篇文章搞定BIO、NIO、AIO、Netty(详细基础内容+网络编程内容+代码示例)【网络编程 2】...

.markdown-body { line-height: 1.75; font-weight: 400; font-size: 16px; overflow-x: hidden; color: rgba(37, 41, 51, 1) } .markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .ma...

程序员小明1024 1199
上一篇: 字符集与字符编码问题
下一篇: 日志系统2
maimode
博客等级 码龄19年 11粉丝 35原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值