java Netty应用实例-群聊系统

2024-04-04 18:44

本文主要是介绍java Netty应用实例-群聊系统,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、实例要求:

1)编写一个Netty群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)

2)实现多人群聊

3)服务器端:可以监测用户上线,离线,并实现消息转发功能。

4)客户端:通过channel可以无阻塞发送消息给其他所有用户,同时可以接受其他用户发送的消息(有服务器转发得到)

5)目的:进一步理解Netty非阻塞网络编程机制。

二、以下为实现代码

1.服务器端GroupChatServer.java

package com.tfq.netty.netty.groupchat;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;/*** @author: fqtang* @date: 2024/04/03/13:39* @description: 描述*/
public class GroupChatServer {//监听端口private int port;public GroupChatServer(int port) {this.port = port;}/*** 处理客户端的请求*/public void run() throws InterruptedException {//创建两个线程组EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup(8);try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {//获取到pipelineChannelPipeline pipeline = ch.pipeline();//向pipeline加入一个解码器pipeline.addLast("decoder", new StringDecoder());//向pipeline加入一个编码器pipeline.addLast("encoder", new StringEncoder());//加入自己的业务处理handlerpipeline.addLast(new GroupChatServerHandler());}});System.out.println("netty 服务器启动");ChannelFuture channelFuture = serverBootstrap.bind(port).sync();channelFuture.channel().closeFuture().sync();}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}public static void main(String[] args) {try {new GroupChatServer(7888).run();} catch(InterruptedException e) {throw new RuntimeException(e);}}}

服务器端的handler处理:

package com.tfq.netty.netty.groupchat;import java.text.SimpleDateFormat;
import java.util.Date;import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;/*** @author: fqtang* @date: 2024/04/03/13:53* @description: 描述*/
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {/*** 定义一个channel组,管理所有的channel* GlobalEventExecutor.INSTANCE是全局的事件执行器,是一个单例*/private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");/*** 表示连接建立,一旦连接,第一个被执行* 将当前channel加入到 channelGroup** @param ctx* @throws Exception*/@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception {Channel channel = ctx.channel();//将该客户加入聊天的信息推送给其他在线的客户端//该方法会将channelGroup 中所有的channel 遍历,并发送消息,我们不需要自己遍历channels.writeAndFlush(sdf.format(new Date())+" [客户端]" + channel.remoteAddress() + " 加入聊天\n");channels.add(channel);}/*** 表示channel 处于活动上线,提示 xx上线** @param ctx* @throws Exception*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println(ctx.channel().remoteAddress() + " 在[ "+sdf.format(new Date())+" ] 上线了~");}/*** 表示channel 处于离线,提示 xx离线** @param ctx* @throws Exception*/@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println(ctx.channel().remoteAddress() + "在 "+sdf.format(new Date())+" 离线了~");}/*** 断开连接,将XX客户离开信息推送给当前在线的客户** @param ctx* @throws Exception*/@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception {Channel channel = ctx.channel();channels.writeAndFlush("[客户端]" + channel.remoteAddress() + "在 【"+ sdf.format(new Date()) +"】 离开\n");System.out.println("移除通道"+channel.hashCode()+",当前通道总数:" + channels.size());}@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {//获取当前通道channelChannel channel = ctx.channel();//这时我们遍历channels,根据不同的情况,返回不同的不同消息channels.forEach(c -> {if(channel !=c){//不是当前的channel,直接打印消息//把当前通道的消息转发给其他通道了c.writeAndFlush("[客户]" + channel.remoteAddress()+ "在 【"+ sdf.format(new Date()) + "】 发送了消息:"+ msg +" \n");}else {c.writeAndFlush("【自己】在 【"+ sdf.format(new Date()) +"】 发送了消息"+msg+"\n");}});}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {//关闭通道ctx.close();System.out.println("在 【"+sdf.format(new Date()) +"】 关闭通道,通道总数:" + channels.size());}
}

2.客户端GroupChatClient.java

package com.tfq.netty.netty.groupchat;import java.util.Scanner;import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;/*** @author: fqtang* @date: 2024/04/04/7:54* @description: 描述*/
public class GroupChatClient {private final String host;private final int port;public GroupChatClient(String host, int port) {this.host = host;this.port = port;}public void run() {EventLoopGroup eventLoopGroup = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {//得到pipelineChannelPipeline pipeline = ch.pipeline();//加入相关handler的解码器pipeline.addLast("decoder", new StringDecoder());//加入相关handler的编码器pipeline.addLast("encoder", new StringEncoder());//加入自定义的handlerpipeline.addLast(new GroupChatClientHandler());}});//连接服务器返回通道ChannelFuture channelFuture = bootstrap.connect(host, port).sync();Channel channel = channelFuture.channel();if(channelFuture.isSuccess()) {System.out.println("本地ip:"+channel.localAddress()+",连接服务器ip: "+channel.remoteAddress() + " 成功");}Scanner scanner = new Scanner(System.in);while(scanner.hasNextLine()) {channel.writeAndFlush(scanner.nextLine());}//给关闭监听进行通道channel.closeFuture().sync();} catch(InterruptedException e) {throw new RuntimeException(e);} finally {eventLoopGroup.shutdownGracefully();}}public static void main(String[] args) {new GroupChatClient("127.0.0.1", 7888).run();}
}

客户端的handler处理

package com.tfq.netty.netty.groupchat;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;/*** @author: fqtang* @date: 2024/04/04/8:16* @description: 描述*/
public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {System.out.println(msg.trim());}
}

先运行GroupChatServer.java,然后运行多个GroupChatClient客户端。若用Idea开发则设置运行多个 客户。如下图:

运行如下图所示:

完毕。

这篇关于java Netty应用实例-群聊系统的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/876566

相关文章

SpringBoot整合liteflow的详细过程

《SpringBoot整合liteflow的详细过程》:本文主要介绍SpringBoot整合liteflow的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...  liteflow 是什么? 能做什么?总之一句话:能帮你规范写代码逻辑 ,编排并解耦业务逻辑,代码

JavaSE正则表达式用法总结大全

《JavaSE正则表达式用法总结大全》正则表达式就是由一些特定的字符组成,代表的是一个规则,:本文主要介绍JavaSE正则表达式用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录常用的正则表达式匹配符正则表China编程达式常用的类Pattern类Matcher类PatternSynta

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

在Spring Boot中集成RabbitMQ的实战记录

《在SpringBoot中集成RabbitMQ的实战记录》本文介绍SpringBoot集成RabbitMQ的步骤,涵盖配置连接、消息发送与接收,并对比两种定义Exchange与队列的方式:手动声明(... 目录前言准备工作1. 安装 RabbitMQ2. 消息发送者(Producer)配置1. 创建 Spr