Netty-07-群聊系统实现

Netty-07-群聊系统实现

前言

实例要求

  • 编写一个Netty 群聊系统,实现客户端和服务端之间的数据简单通信(非阻塞)
  • 实现多人群聊
  • 服务器端: 可以检测用户上线,离线,并实现消息的转发
  • 客户端:通过channel 可以无阻塞发送消息给其他用户,同时可以接受其他用户发送来的消息(由)服务器转发得到
  • 目的 : 进一步理解Netty 非阻塞网络编程机制

1. 服务端代码

1.1 启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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.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;

public class GroupChatServer {

private int port;
public GroupChatServer(int port) {
this.port = port;
}


// 编写run 方法,处理客户端请求
public void run() throws InterruptedException{
// 创建两个线程组
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();

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>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("decoder",new StringDecoder());
pipeline.addLast("encoder",new StringEncoder());
pipeline.addLast(new GroupChatHandler());
}
});

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) throws InterruptedException {
GroupChatServer groupChatServer = new GroupChatServer(7000);
groupChatServer.run();
}
}

1.2 Handler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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;

// 处理器
public class GroupChatHandler extends SimpleChannelInboundHandler<String> {
// 定义一个channel组,管理所有的channel
// GlobalEventExecutor.INSTANCE 是全局事件执行器,是一个单例
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// 此方法表示连接建立,一旦建立连接就第一个被执行
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
// 该方法会将channelGroup 中所有的channel 遍历,并发送消息而不需要我们自己去遍历
channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + sdf.format(new Date()) + "加入了聊天");
// 将当前的Channel 加入到 channelGroup
channelGroup.add(channel);
}

// 表示channel 处于活动状态,提示XXX已经上线
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " " + sdf.format(new Date()) + "上线了~");
}

// 表示channel 断开连接,将xx客户端离开信息推送给当前在线用户
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " " + sdf.format(new Date()) + "离线了~");
}

@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
// channel 关闭后会自动remove掉
Channel channel = ctx.channel();
channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() +" "+ sdf.format(new Date()) + "离开了\n");
System.out.println("当前channelGroup大小 :" + channelGroup.size());
}

// 读取数据进行消息的转发
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// 获取当前的channel
Channel channel = ctx.channel();

// 遍历channelGroup 根据不同的情况回显不同的消息
channelGroup.forEach(item -> {
if (item != channel){
item.writeAndFlush("[客户]" + channel.remoteAddress() + "发送了消息:" + msg + "\n");
}else{
item.writeAndFlush("[自己]发送了消息:" + msg + "\n");
}
});
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}

2. 客户端代码

2.1 客户端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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.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;

import java.util.Scanner;

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() throws InterruptedException{
NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

try {
Bootstrap bootstrap = new Bootstrap()
.group(eventExecutors)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//加入Handler
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast(new GroupChatClientHandler());
}
});


// connect 事件
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
// 得到channel,打印本地地址
Channel channel = channelFuture.channel();
System.out.println("--------" + channel.localAddress() + "---------");


// 客户端需要输入信息
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
// 通过channel 发送到服务器端
channel.writeAndFlush(msg + "\r\n");
}
}finally {
eventExecutors.shutdownGracefully();
}
}

public static void main(String[] args) throws InterruptedException {
new GroupChatClient("127.0.0.1",7000).run();
}
}

2.2 Handler

1
2
3
4
5
6
7
8
9
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg.trim());
}
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信