网络编程-NIO案例 与 AIO 案例

案例说明:一个简单的群聊实现,支持重复上下线。

NIO

服务端

public class NIOServer {public static void main(String[] args) throws IOException {ServerSocketChannel serverChannel = ServerSocketChannel.open();// 初始化服务器serverChannel.bind(new InetSocketAddress(9999));Selector selector = Selector.open();serverChannel.configureBlocking(false);serverChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {// 每过两秒中来看是否有请求过来if (selector.select(2000) != 0) {System.out.println("===================");Iterator<SelectionKey> it = selector.selectedKeys().iterator();try {String ipStr = "";while (it.hasNext()) {SelectionKey next = it.next();// 建立连接if (next.isAcceptable()) {ByteBuffer bu = ByteBuffer.allocate(1024);SocketChannel channel = serverChannel.accept();channel.configureBlocking(false);channel.register(selector, SelectionKey.OP_READ, bu);ipStr = channel.getRemoteAddress().toString().substring(1);System.out.println(ipStr + "上线 ...");}// 读取数据if (next.isReadable()) {SocketChannel channel = (SocketChannel) next.channel();// 如果这个时候通道已经关闭了if (!channel.isOpen()) {next.cancel();return;}try {channel.configureBlocking(false);ByteBuffer buffer = (ByteBuffer) next.attachment();channel.read(buffer);String msg = new String(buffer.array(), 0, buffer.position());System.out.println("receive : " + msg);// 广播消息broadCast(selector, channel, msg);buffer.clear();} catch (Exception e) {System.out.println("======================发生异常进行下线操作=========");next.cancel();it.remove();continue;}}it.remove();}} catch (Exception e) {e.printStackTrace();}}}}public static void broadCast(Selector selector, SocketChannel channel, String msg) throws IOException {Set<SelectionKey> keys = selector.keys();Iterator<SelectionKey> iterator = keys.iterator();while (iterator.hasNext()) {SelectionKey next = iterator.next();SelectableChannel targetChannel = next.channel();// 如果被广播的对象连接还在if (targetChannel.isOpen()) {if (targetChannel instanceof SocketChannel && channel != targetChannel) {((SocketChannel) targetChannel).write(ByteBuffer.wrap(msg.getBytes()));}} else {// 表示通道不存在了 进行下线操作next.cancel();}}}
}

客户端

public class NIOClient {private SocketChannel channel;private String userName;private String bindIP;private int bindPort;public NIOClient(String userName, String bindIP, int bindPort) throws IOException {channel = SocketChannel.open();channel.configureBlocking(false);this.bindIP = bindIP;this.bindPort = bindPort;channel.connect(new InetSocketAddress(bindIP, bindPort));this.userName = userName;while (!channel.finishConnect()) {// 等待连接成功}}public void sendMsg(String msg) throws IOException {if (msg == "end") {channel.close();return;}msg = "from " + this.userName + " : " + msg;channel.write(ByteBuffer.wrap(msg.getBytes()));}public void receive() throws IOException {ByteBuffer buffer = ByteBuffer.allocate(1024);int size = channel.read(buffer);if(size>0){String msg=new String(buffer.array());System.out.println(msg.trim());}}
}
// Main 函数
public static void main(String[] args) throws IOException {new Thread(() -> {final NIOClient nioClient;try {nioClient = new NIOClient("one", "127.0.0.1", 9999);} catch (IOException e) {throw new RuntimeException(e);}Thread thread = new Thread(() -> {try {while (true) {nioClient.receive();Thread.sleep(3000);}} catch (IOException e) {throw new RuntimeException(e);} catch (InterruptedException e) {System.out.println("=============== 离线 ===================");}});thread.start();;System.out.println( "one pleas input : ");Scanner scanner = new Scanner(System.in);String msg = "";while (!(msg = scanner.nextLine()).equals("end")) {try {nioClient.sendMsg(msg);} catch (IOException e) {e.printStackTrace();throw new RuntimeException(e);}}thread.interrupt();}).start();
};

AIO

public class NettyServer {public static void main(String[] args) {NioEventLoopGroup boosGroup = new NioEventLoopGroup();NioEventLoopGroup workGroup = new NioEventLoopGroup();try {ServerBootstrap bootstrap = new ServerBootstrap();bootstrap.group(boosGroup, workGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();pipeline.addLast("decoder", new StringDecoder());pipeline.addLast("encoder", new StringEncoder());pipeline.addLast(new NettyChatServerHandler());}});ChannelFuture f = bootstrap.bind(9999).sync();f.channel().closeFuture().sync();} catch (Exception e) {e.printStackTrace();} finally {boosGroup.shutdownGracefully();workGroup.shutdownGracefully();System.out.println("关闭");}}
}
public class NettyChatServerHandler extends SimpleChannelInboundHandler<String> {public static List<Channel> channels = new ArrayList<>();@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {Channel channel = ctx.channel();channels.add(channel);System.out.println(channel.remoteAddress().toString().substring(1) + " online");}@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {Channel channel = ctx.channel();for (Channel ch : channels) {if (ch != channel) {ch.writeAndFlush("["+ch.remoteAddress().toString().substring(1)+"]"+"said:"+s+"\n");}}}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {Channel channel = ctx.channel();channels.remove(channel);System.out.println(channel.remoteAddress().toString().substring(1) + " off line");}
}
public class ChatClient {private String host;private int port;public ChatClient(String host, int port) {this.host = host;this.port = port;}public void run() {NioEventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();pipeline.addLast("decoder", new StringDecoder());pipeline.addLast("encoder", new StringEncoder());pipeline.addLast(new NettyClientHandler());}});ChannelFuture sync = bootstrap.connect(new InetSocketAddress("127.0.0.1",9999)).sync();Channel channel = sync.channel();Scanner scanner = new Scanner(System.in);while (scanner.hasNextLine()) {String msg = scanner.nextLine();channel.writeAndFlush(msg + "\\r\\n").sync();}sync.channel().closeFuture().sync();} catch (Exception e) {e.printStackTrace();} finally {group.shutdownGracefully();}}
}
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {System.out.println(s.trim());}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/702034.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

token的有状态和无状态

在身份验证和授权领域&#xff0c;"有状态"&#xff08;stateful&#xff09;和"无状态"&#xff08;stateless&#xff09;通常用来描述系统处理用户认证信息的方式。 有状态&#xff08;Stateful&#xff09;&#xff1a; 有状态的认证系统在服务器端会维…

uvloop,一个强大的 Python 异步IO编程库!

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站零基础入门的AI学习网站~。 目录 ​编辑 前言 什么是uvloop库&#xff1f; 安装uvloop库 使用uvloop库 uvloop库的功能特性 1. 更…

DPDK常用API合集二

网络数据包缓冲管理&#xff08;librte_mbuf&#xff09; 1.1 rte_pktmbuf_alloc 是 DPDK&#xff08;数据平面开发工具包&#xff09;中的一个函数&#xff0c;用于在内存池中分配一个新的 mbuf&#xff08;内存缓冲区&#xff09; struct rte_mbuf *rte_pktmbuf_alloc(stru…

Spring ReflectionUtils 反射工具介绍和使用

一、ReflectionUtils 在 Java 中&#xff0c;反射&#xff08;Reflection&#xff09;是一种强大的机制&#xff0c;允许程序在运行时动态地检查类、获取类的信息、调用类的方法、访问或修改类的属性等。Java 的反射机制提供了一组类和接口&#xff0c;位于 java.lang.reflect…

WebLogic Server JNDI注入漏洞复现(CVE-2024-20931)

0x01 产品简介 Oracle WebLogic Server 是一个Java应用服务器,它全面实现了J2EE 1.5规范、最新的Web服务标准和最高级的互操作标准。WebLogic Server内核以可执行、可扩展和可靠的方式提供统一的安全、事务和管理服务。Oracle Fusion Middleware(Oracle融合中间件)和Oracle…

【二分查找】【浮点数的二分查找】【二分答案查找】

文章目录 前言一、二分查找&#xff08;Binary Search&#xff09;二、浮点数的二分查找三、二分答案总结 前言 今天记录一下基础算法之二分查找 一、二分查找&#xff08;Binary Search&#xff09; 二分查找&#xff08;Binary Search&#xff09;是一种在有序数组中查找目…

Nodejs+vue图书阅读评分个性化推荐系统

此系统设计主要采用的是nodejs语言来进行开发&#xff0c;采用 vue框架技术&#xff0c;对于各个模块设计制作有一定的安全性&#xff1b;数据库方面主要采用的是MySQL来进行开发&#xff0c;其特点是稳定性好&#xff0c;数据库存储容量大&#xff0c;处理能力快等优势&#x…

效率系列(九) macOS入门各式快捷操作

大家好&#xff0c;我是半虹&#xff0c;这篇文章来讲 macOS 中的各式快捷操作 零、序言 快捷操作这种东西&#xff0c;看得再多&#xff0c;不如实际用起来&#xff0c;用习惯之后&#xff0c;真的会感受到效率提高的 所以这篇文章主要是想总结下常用的触控板手势和键盘快捷…

数字热潮:iGaming 能否推动加密货币的普及?

过去十年&#xff0c;iGaming&#xff08;互联网游戏&#xff09;世界有了显著增长&#xff0c;每月有超过一百万的新用户加入。那么&#xff0c;这一主流的秘密是什么&#xff1f;让我们在本文中探讨一下。 领先一步&#xff1a;市场 数字时代正在重新定义娱乐&#xff0c;iG…

MySQL运维实战(7.2) MySQL复制server_id相关问题

作者&#xff1a;俊达 主库server_id没有设置 主库没有设置server_id Got fatal error 1236 from master when reading data from binary log: Misconfigured master - server_id was not set主库查看server_id mysql> show variables like server_id; ----------------…

如何在本地电脑部署HadSky论坛并发布至公网可远程访问【内网穿透】

文章目录 前言1. 网站搭建1.1 网页下载和安装1.2 网页测试1.3 cpolar的安装和注册 2. 本地网页发布2.1 Cpolar临时数据隧道2.2 Cpolar稳定隧道&#xff08;云端设置&#xff09;2.3 Cpolar稳定隧道&#xff08;本地设置&#xff09;2.4 公网访问测试 总结 前言 经过多年的基础…

哈希表在Java中的使用和面试常见问题

当谈到哈希表在Java中的使用和面试常见问题时&#xff0c;以下是一些重要的点和常见问题&#xff1a; 哈希表在Java中的使用 HashMap 和 HashTable 的区别&#xff1a; HashMap 和 HashTable 都实现了 Map 接口&#xff0c;但它们有一些重要的区别&#xff1a; HashMap 是非线…

Repeater:创建大量类似项

Repeater 类型用于创建大量类似项。与其它视图类型一样&#xff0c;Repeater有一个model和一个delegate。 首次创建Repeater时&#xff0c;会创建其所有delegate项。若存在大量delegate项&#xff0c;并且并非所有项都必须同时可见&#xff0c;则可能会降低效率。 有2种方式可…

【ubuntu】永久修改主机名

文章目录 1. 问题描述2. 解决方案 1. 问题描述 主机名过长&#xff08;后面的部分&#xff09; 2. 解决方案 查看主机名详情 hostnamectl修改指定主机名 hostnamectl set-hostname ubuntu2204 --static登出重进即可

冯诺依曼体系结构 与 操作系统

一、冯诺依曼体系结构 深入理解冯诺依曼体系结构 计算机的出现就是为了解决实际问题, 所以把问题交给计算机&#xff0c;计算机经过处理&#xff0c;得到一个结果反馈给我们&#xff0c;所以这中间就必然涉及到了输入设备&#xff0c;中央处理器(包括运算器和控制器)和输出设备…

Markdown笔记

1、标题 # 一级标题 ## 二级标题 ### 三级标题 #### 四级标题 ##### 五级标题 ###### 六级标题一级标题 二级标题 三级标题 四级标题 五级标题 六级标题 2、文本样式 *强调文本* _强调文本_**加粗文本** __加粗文本__标记文本~~删除文本~~> 引用文本H~2~O is是液体。…

【HarmonyOS】低代码开发—使用低代码开发服务卡片

DevEco Studio还支持使用低代码开发功能开发服务卡片&#xff0c;目前只支持JS语言&#xff0c;且compileSdkVersion必须为7或以上。 下面以创建一个新的服务卡片为例进行说明。 1.打开一个工程&#xff0c;创建服务卡片&#xff0c;创建方法包括如下两种方式&#xff1a; 选…

网络安全“三保一评”深度解析

“没有网络安全就没有国家安全”。近几年&#xff0c;我国法律法规陆续发布实施&#xff0c;为承载我国国计民生的重要网络信息系统的安全提供了法律保障&#xff0c;正在实施的“3保1评”为我国重要网络信息系统的安全构筑了四道防线。 什么是“3保1评”&#xff1f; 等保、分…

计算机网络-网络互联

文章目录 网络互联网络互联方法LAN-LAN&#xff1a;网桥及其互连原理使用网桥实现LAN-LAN使用交换机扩展局域网使用路由器连接局域网 LAN-WANWAN-WAN路由选择算法非自适应路由选择算法自适应路由选择算法广播路由选择算法&#xff1a;分层路由选择算法 网络互联 网络互联是指利…

我的128创作纪念日

目录 学习成长机遇个人数据一览榜单认可日常2024憧憬和规划创作纪念日总结 学习成长机遇 账号创建已经快9年了&#xff0c;以前一直在个人网站和简书上写文章&#xff0c;在CSDN真正写文竟然在2023年10月20&#xff0c;至今才128天&#xff0c;不过获得的数据还算可以&#xff…