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

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

Redis中Stream详解及应用小结

《Redis中Stream详解及应用小结》RedisStreams是Redis5.0引入的新功能,提供了一种类似于传统消息队列的机制,但具有更高的灵活性和可扩展性,本文给大家介绍Redis中Strea... 目录1. Redis Stream 概述2. Redis Stream 的基本操作2.1. XADD

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads