netty实现群聊功能
【概述】
实现一个网络群聊工具。参与聊天的客户端消息是通过服务端进行广播的。
主要由两块组成:聊天服务器端(ChatServer)和聊天客户端(ChatClient)。
聊天服务器(ChatServer)功能概述 :
1.监听所有客户端的接入、断线
2.有客户端A接入聊天室时,将接入消息发给除了客户端A的其他客户端
3.当客户端A退出聊天室时,将退出消息发给除了客户端A的其他客户端
4.当客户端A发送消息到聊天室时,将消息转发给除了客户端A的其他客户端
聊天客户端(ChatClient)功能概述 :
1.发送消息至聊天服务器
2.接收聊天服务器发送过来的所有消息
【pom依赖】
<!--netty-->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.36.Final</version>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
【服务端启动器 ChatServer 】
package com.test.server; 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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; /**
* 群聊服务端
*
*/
public class ChatServer {
private final int port; public ChatServer(int port) {
this.port = port;
} public void start() throws InterruptedException {
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup childGroup = new NioEventLoopGroup(); try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel sc) throws Exception {
ChannelPipeline pipeline = sc.pipeline();
//添加一个基于行的解码器
pipeline.addLast(new LineBasedFrameDecoder(2048));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ChatServerHandler());
} }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = serverBootstrap.bind(port).sync();
System.out.println("服务器已启动");
future.channel().closeFuture().sync();
} finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
} public static void main(String[] args) throws InterruptedException {
new ChatServer(8888).start();
}
}
【ChatServerHandler】
package com.test.server; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor; /**
* 处理聊天服务器的各种情况
*
*/
public class ChatServerHandler extends ChannelInboundHandlerAdapter {
// 创建一个ChannelGroup,其是一个线程安全的集合,其中存放着与当前服务器相连接的所有Active状态的Channel
// GlobalEventExecutor是一个单例、单线程的EventExecutor,是为了保证对当前group中的所有Channel的处理
// 线程是同一个线程
private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); // 只要有客户端Channel给当前的服务端发送了消息,那么就会触发该方法的执行
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 获取到向服务器发送消息的channel
Channel channel = ctx.channel();
// 这里要实现将消息广播给所有group中的客户端Channel
// 发送给自己的消息与发送给大家的消息是不一样的
group.forEach(ch -> {
if (ch != channel) {
ch.writeAndFlush(channel.remoteAddress() + ":" + msg + "\n");
} else {
channel.writeAndFlush("me:" + msg + "\n");
}
});
} // 只要有客户端Channel与服务端连接成功就会执行这个方法
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 获取到当前与服务器连接成功的channel
Channel channel = ctx.channel();
System.out.println(channel.remoteAddress() + "---上线");
group.writeAndFlush(channel.remoteAddress() + "---上线\n");
// 将当前channel添加到group中
group.add(channel);
} // 只要有客户端Channel断开与服务端的连接就会执行这个方法
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 获取到当前要断开连接的Channel
Channel channel = ctx.channel();
System.out.println(channel.remoteAddress() + "------下线");
group.writeAndFlush(channel.remoteAddress() + "下线,当前在线人数:" + group.size() + "\n"); // group中存放的都是Active状态的Channel,一旦某Channel的状态不再是Active,
// group会自动将其从集合中踢出,所以,下面的语句不用写
// remove()方法的应用场景是,将一个Active状态的channel移出group时使用
// group.remove(channel);
} /**
* 当Channel中的数据在处理过程中出现异常时会触发该方法的执行
*
* @param ctx 上下文
* @param cause 发生的异常对象
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} }
【客户端启动类ChatClient】
package com.test.client; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; /**
* 群聊客户端
*
*/
public class ChatClient {
private final String host; private final int port; public ChatClient(String host, int port) {
this.host = host;
this.port = port;
} public void start() {
NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LineBasedFrameDecoder(2048));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ChatClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
// 获取键盘输入
InputStreamReader is = new InputStreamReader(System.in, "UTF-8");
BufferedReader br = new BufferedReader(is);
// 将输入的内容写入到Channel
while (true) {
//br.readLine()中执行fill()方法获取输入数据,获取不到时会发生阻塞,直到获取到数据为止
future.channel().writeAndFlush(br.readLine() + "\r\n");
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
} public static void main(String[] args) {
new ChatClient("127.0.0.1", 8888).start();
}
}
【ChatClientHandler】
package com.test.client; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; /**
* 客户端处理
*
*/
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println(s);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
【运行结果】
[1.启动群聊服务端]

[2.启动群聊客户端01]


[2.启动群聊客户端02]



[3.发送消息测试]


[4.下线测试]


netty实现群聊功能的更多相关文章
- Java-->实现群聊功能(C/S模式--TCP协议)
--> Java 对TCP协议的支持: --> java.net包中定义了两个类ServerSocket 和Socket ,分别用来实现双向连接的server 端和client 端. -- ...
- day04-1群聊功能
多用户即时通讯系统04 4.编码实现03 4.5功能实现-群聊功能实现 4.5.1思路分析 群聊的实现思路和私聊的实现非常类似. 不同的是:私聊时,服务端接收到消息后,只需要找出接收方的socket并 ...
- netty无缝切换rabbitmq、activemq、rocketmq实现聊天室单聊、群聊功能
netty的pipeline处理链上的handler:需要IdleStateHandler心跳检测channel是否有效,以及处理登录认证的UserAuthHandler和消息处理MessageHan ...
- Asp.net SignalR 应用并实现群聊功能 开源代码
ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 Web 功能是指这样一种功能:当所连接的客户端变得可用时服务 ...
- ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(四) 添加表情、群聊功能
休息了两天,还是决定把这个尾巴给收了.本篇是最后一篇,也算是草草收尾吧.今天要加上表情功能和群聊.基本上就差不多了,其他功能,读者可以自行扩展或者优化.至于我写的代码方面,自己也没去重构.好的,我们开 ...
- java项目-----客户端与客户端通信--实现群聊功能的代码
这是这个网络聊天室项目的原理图: 很简单,首先ABCD是4个客户端,当A发送信息给服务器,服务器实现以广播的形式把信息全发给每个人---群发群聊 客户端代码: package com.aa; impo ...
- Websocket 群聊功能
websocket 群聊 前提关闭防火墙 写入代码 from flask import Flask,request,render_template from geventwebsocket.handl ...
- 基于koa模块和socket.io模块搭建的node服务器实现通过jwt 验证来渲染列表、私聊、群聊功能
1. 具体代码在需要的下载 https://gitee.com/zyqwasd/socket 效果: 2. package.json文件 1. 下载基本的模块 修改了start 脚本 nodemo ...
- 基于netty实现单聊、群聊功能
学习资料 https://juejin.im/book/5b4bc28bf265da0f60130116/section/5b6a1a9cf265da0f87595521 收获: 转载 1. Nett ...
随机推荐
- 带你学习Javascript中的函数进阶(一)
1. 函数的定义和调用 1.1 函数的定义方式 函数声明方式function关键字(命名函数) 函数表达式(匿名函数) new Function() var fn = new Function('参数 ...
- 【Art】抗疫路上,温暖相伴
2020年3月. 本应是春暖花开的时节,武汉却是寒冷的,整个中国也是寒冷的. 疫情将人们逼得退无可退,只能待在家里看着电视新闻与手机上一个个数字不断跳动,等待着它们背后前线的无数命悬一线的战士的胜利讯 ...
- Swift--struct与class的区别(汇编角度底层分析)
概述 相对Objective-C, Swift使用结构体Struct的比例大大增加了,其中Int, Bool,以及String,Array等底层全部使用Struct来定义!在Swift中结构体不仅可以 ...
- Web图片资源的加载与渲染时机
此文研究页面中的图片资源的加载和渲染时机,使得我们能更好的管理图片资源,避免不必要的流量和提高用户体验. 浏览器的工作流程 要研究图片资源的加载和渲染,我们先要了解浏览器的工作原理.以Webkit引擎 ...
- python入门到放弃-基本数据类型之tuple元组
#概述 元组俗称不可变的列表,又称只读列表,是python的基本数据类型之一, 用()小括号表示,里面使用,逗号隔开 元组里面可以放任何的数据类型的数据,查询可以,循环可以,但是就是不能修改 #先来看 ...
- 2019年最新老男孩高性能Web架构与自动化运维架构视频教程
课程目录L001-老男孩架构15期-Web架构之单机时代L002-老男孩架构15期-Web架构之集群时代L003-老男孩架构15期-Web架构之dnsL004-老男孩架构15期-Web架构之缓存体系L ...
- 本地目录配置多个远程Git仓库
目录 情景一:不同的库分别 pull/push 1. 使用git命令配置 2. 修改.git/config 文件 3. 操作 情景二:不同的库一次push 1. 使用git命令配置 2. 修改.git ...
- linux firewalld 防火墙操作命令
查看防火墙的状态systemctl status firewalldTomcat默认使用8080端口,如果防火墙开启,需要开通8080端口firewall-cmd --zone=public --ad ...
- Fabric 源码学习:如何实现批量管理远程服务器?
前不久,我写了一篇<Fabric教程>,简单来说,它是一个用 Python 开发的轻量级的远程系统管理工具,在远程登录服务器.执行 Shell 命令.批量管理服务器.远程部署等场景中,十分 ...
- 【06】openlayers 切片图层
创建地图: //OSM图层 let source = new ol.source.OSM() //切片图层tilelayer let layers = new ol.layer.Tile({ sour ...