功能介绍

使用Netty框架实现聊天室功能,服务器可监控客户端上下限状态,消息转发。同时实现了点对点私聊功能。技术点我都在代码中做了备注,这里不再重复写了。希望能给想学习netty的同学一点参考。

服务器代码

服务器入口代码

package nio.test.netty.groupChat;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
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;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;/*** netty群聊 服务器端* @author zhang**/
public class NettyChatServer {private int port;public NettyChatServer(int port){this.port = port;}//初始化 netty服务器private void init() throws Exception{EventLoopGroup boss = new NioEventLoopGroup(1);EventLoopGroup work = new NioEventLoopGroup(16);try {ServerBootstrap boot = new ServerBootstrap();boot.group(boss,work);boot.channel(NioServerSocketChannel.class);//设置boss selector建立channel使用的对象boot.option(ChannelOption.SO_BACKLOG, 128);//boss 等待连接的 队列长度boot.childOption(ChannelOption.SO_KEEPALIVE, true); //让客户端保持长期活动状态boot.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {//从channel中获取pipeline 并往里边添加HandlerChannelPipeline pipeline = ch.pipeline();pipeline.addLast("encoder",new StringEncoder());pipeline.addLast("decoder",new StringDecoder());pipeline.addLast(new ServerMessageHandler());//自定义Handler来处理消息}});System.out.println("服务器开始启动...");//绑定端口 ChannelFuture channelFuture = boot.bind(port).sync();channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {@Overridepublic void operationComplete(Future<? super Void> future)throws Exception {if(future.isSuccess()){System.out.println("服务器正在启动...");}if(future.isDone()){System.out.println("服务器启动成功...OK");}}});//监听channel关闭channelFuture.channel().closeFuture().sync();channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {@Overridepublic void operationComplete(Future<? super Void> future)throws Exception {if(future.isCancelled()){System.out.println("服务器正在关闭..");}if(future.isCancellable()){System.out.println("服务器已经关闭..OK");}}});}finally{boss.shutdownGracefully();work.shutdownGracefully();}}/*** 启动服务器 main 函数* @param args* @throws Exception*/public static void main(String[] args) throws Exception {new NettyChatServer(9090).init();}}

服务器端消息处理Handler

package nio.test.netty.groupChat;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;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/*** 自定义 服务器端消息处理Handler* @author zhang**/
public class ServerMessageHandler extends SimpleChannelInboundHandler<String>{/*** 管理全局的channel* GlobalEventExecutor.INSTANCE  全局事件监听器* 一旦将channel 加入 ChannelGroup 就不要用手动去* 管理channel的连接失效后移除操作,他会自己移除*/private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);/*** 为了实现私聊功能,这里key存储用户的唯一标识,* 我保存 客户端的端口号* 当然 这个集合也需要自己去维护 用户的上下线 不能像 ChannelGroup那样自己去维护*/private static Map<String,Channel> all = new HashMap<String,Channel>();private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");/*** 处理收到的消息*/@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg)throws Exception {Channel channel = ctx.channel();/*** 这里简单判断 如果内容里边包含#那么就是私聊*/if(msg.contains("#")){String id = msg.split("#")[0];String body = msg.split("#")[1];Channel userChannel = all.get(id);String key = channel.remoteAddress().toString().split(":")[1];userChannel.writeAndFlush(sf.format(new Date())+"\n 【用户】 "+key+" 说 : "+body);return;}//判断当前消息是不是自己发送的for(Channel c : channels){String addr = c.remoteAddress().toString();if(channel !=c){c.writeAndFlush(sf.format(new Date())+"\n 【用户】 "+addr+" 说 : "+msg);}else{c.writeAndFlush(sf.format(new Date())+"\n 【自己】 "+addr+" 说 : "+msg);}}}/*** 建立连接以后第一个调用的方法*/@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception {Channel channel = ctx.channel();String addr = channel.remoteAddress().toString();/*** 这里 ChannelGroup 底层封装会遍历给所有的channel发送消息* */channels.writeAndFlush(sf.format(new Date())+"\n 【用户】 "+addr+" 加入聊天室 ");channels.add(channel);String key = channel.remoteAddress().toString().split(":")[1];all.put(key, channel);}/*** channel连接状态就绪以后调用*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {String addr = ctx.channel().remoteAddress().toString();System.out.println(sf.format(new Date())+" \n【用户】 "+addr+" 上线 ");}/*** channel连接状态断开后触发*/@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {String addr = ctx.channel().remoteAddress().toString();System.out.println(sf.format(new Date())+" \n【用户】 "+addr+" 下线 ");//下线移除String key = ctx.channel().remoteAddress().toString().split(":")[1];all.remove(key);}/*** 连接发生异常时触发*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {//System.out.println("连接发生异常!");ctx.close();}/*** 断开连接会触发该消息* 同时当前channel 也会自动从ChannelGroup中被移除*/@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception {Channel channel = ctx.channel();String addr = channel.remoteAddress().toString();/*** 这里 ChannelGroup 底层封装会遍历给所有的channel发送消息* */channels.writeAndFlush(sf.format(new Date())+"\n 【用户】 "+addr+" 离开了 ");//打印 ChannelGroup中的人数System.out.println("当前在线人数是:"+channels.size());System.out.println("all:"+all.size());}}

客户端主方法代码

package nio.test.netty.groupChat;import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;import java.util.Scanner;public class NettyChatClient {private String ip;private int port;public NettyChatClient(String ip,int port){this.ip = ip;this.port = port;}/*** 初始化客户*/private void init() throws Exception{//创建监听事件的监听器EventLoopGroup work = new NioEventLoopGroup();try {Bootstrap boot = new Bootstrap();boot.group(work);boot.channel(NioSocketChannel.class);boot.handler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch)throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("encoder",new StringEncoder());pipeline.addLast("decoder",new StringDecoder());pipeline.addLast(new ClientMessageHandler());}});ChannelFuture channelFuture = boot.connect(ip, port).sync();channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {@Overridepublic void operationComplete(Future<? super Void> future)throws Exception {if(future.isSuccess()){System.out.println("客户端启动中...");}if(future.isDone()){System.out.println("客户端启动成功...OK!");}}});System.out.println(channelFuture.channel().localAddress().toString());System.out.println("#################################################");System.out.println("~~~~~~~~~~~~~~端口号#消息内容~~这样可以给单独一个用户发消息~~~~~~~~~~~~~~~~~~");System.out.println("#################################################");/*** 这里用控制台输入数据*/Channel channel = channelFuture.channel();//获取channelScanner scanner = new Scanner(System.in);while(scanner.hasNextLine()){String str = scanner.nextLine();channel.writeAndFlush(str+"\n");}channelFuture.channel().closeFuture().sync();scanner.close();} finally {work.shutdownGracefully();}}/*** 主方法入口* @param args* @throws Exception*/public static void main(String[] args) throws Exception{new NettyChatClient("127.0.0.1",9090).init();}}

客户端消息处理Handler

package nio.test.netty.groupChat;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/*** 客户点消息处理 Handler* @author zhang**/
public class ClientMessageHandler extends SimpleChannelInboundHandler<String> {/*** 处理收到的消息*/@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg)throws Exception {System.out.println(msg);}/*** 连接异常后触发*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {ctx.close();}
}

测试结果

启动了四个客户端 服务器端日志效果如下:

客户端一端日志:

客户端二日志:

客户端三日志:

客户端四日志:

现在在客户端四发送消息:

每个客户端都可以收到消息:



软化关闭客户端客户端三:
服务器日志:

其他客户端日志:



发送私聊消息:

这个客户端收不到消息

JAVA Netty实现聊天室+私聊功能相关推荐

  1. 微信公众号聊天室 私聊功能演示

    下图是俩功能, 收到消息后, 可有微信推送提醒 1. 点击头像和用户私聊 2. 点击顶部联系管理菜单, 主动与客服管理私聊 效果图预览

  2. java实现多人聊天室+私聊+Derby数据库

    java实现多人聊天室+私聊+Derby数据库(没有实现注册功能) 这个聊天室困扰了我好久好久,一步一步的修改,终于不负我的努力啊,可算完成了,对于一个初学java的来说,完成第一个比较完整的项目,也 ...

  3. Netty实现聊天室

    文章目录 注:更多netty相关文章请访问博主专栏: netty专栏 本文内容基于上一篇博客 netty实现WebSocket协议,一些基本使用请参考该博客. 本例实现的功能: 有新成员加入时,群广播 ...

  4. java web聊天室论文_基于Java网页版聊天室的设计与实现毕业论文含开题报告及文献综述(样例3)...

    <基于Java网页版聊天室的设计与实现毕业论文含开题报告及文献综述.doc>由会员分享,可免费在线阅读全文,更多与<基于Java网页版聊天室的设计与实现毕业论文含开题报告及文献综述& ...

  5. Java大作业——聊天室

    源码 功能概述 用户上线下线,登录和注册功能,群聊和私聊功能,统计聊天室在线人数功能. 文件说明 LoginController:登陆界面的控制器 LoginLauch:整个程序的启动器 Privat ...

  6. netty加载html文件的原理,Netty+html聊天室入门

    1)服务端 ChatServer.java package chat; import chat.handler.WSServerInitializer; import io.netty.bootstr ...

  7. java多人聊天室与网络画板

    本篇主要是对本人前一篇通信博客在部分功能和代码结构上的优化,以下为前篇博客的地址: java通信-网络聊天室&网络画板(简陋版) 一.代码结构上的优化: 对前篇博客服务器类中最后流的关闭上代码 ...

  8. 基于Java+Swing实现聊天室

    基于Java+Swing实现聊天室 一.系统介绍 二.功能展示 三.其它 1.其他系统实现 四.获取源码 一.系统介绍 Java聊天室系统主要用于实现在线聊天,基本功能包括:服务端和客户端.本系统结构 ...

  9. java仿QQ聊天室群聊(快速写一个简易QQ)

    [mie haha的博客]转载请注明出处(万分感谢!): https://blog.csdn.net/qq_40315080/article/details/83052689 用java写聊天室实现群 ...

  10. java web聊天室论文_基于java网页版聊天室的设计与实现毕业论文含开题报告及文献综述.doc...

    基于java网页版聊天室的设计与实现毕业论文含开题报告及文献综述.doc 还剩 52页未读, 继续阅读 下载文档到电脑,马上远离加班熬夜! 亲,很抱歉,此页已超出免费预览范围啦! 如果喜欢就下载吧,价 ...

最新文章

  1. solr的安装配置与helloworld
  2. java cdata xml 解析,如何解析lt;![CDATA []]gt;的XML
  3. 板子ping不通PC怎么办——韦东山嵌入式Linux学习笔记07
  4. emmap erlang_erlang的map基本使用
  5. GDCM:使用Stream Image Writer伪造图像的测试程序
  6. 计算机文化基础主要讲了什么,计算机文化基础—讲义
  7. 使用Cloud Studio写python
  8. 小票上为啥指甲能划出印_指甲上出现竖纹,除遗传问题,或是身体在向你拉警报了,别忽视...
  9. window7 64位下Android studio 安装genymotion模拟器
  10. 【3D文件格式解析】.obj + .mtl
  11. ghost网络克隆功能实现【批量】计算机操作【系统的安装】,网克(诚龙网维全自动PXE网刻工具)批量使用GHOST方法...
  12. (Applied Intelligence-2022)TransGait: 基于多模态的步态识别与集合Transformer
  13. 几种ARM编译器及IDE开发环境
  14. 做sxy官网的一点经验
  15. 生成的分子图像是否可以识别为SMILES,然后再将识别后的SMILES转换为图像?
  16. Libgdx Box2D实战---放开那小球(二:Box2D介绍)
  17. python开发工具geany_geany作为Python的编辑器好用吗?
  18. 浮点数 C语言 IEEE754
  19. mysql qc_MySQL数据库编程中QC的使用方法
  20. C语言实现 二叉树 对任意类型数据的遍历、叶子节点统计、树高计算

热门文章

  1. 第2次作业——时事点评
  2. Admin5推荐软文推广采用“链接标准化”
  3. u3d occlusion 遮挡剔除
  4. JAVA设计模式-11-代理模式(动态)(一)
  5. 电商型网站要怎么制作?把住这三个关键点
  6. 超难打地鼠 【安卓游戏】
  7. 批发商/分销商会有一波向B2B转型的浪潮
  8. android开发--不安装支付宝客户端调H5页面问题
  9. Linux kernel ‘aac_send_raw_srb’函数输入验证漏洞
  10. 域自适应(Domain Adaptation)简介