编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
实现多人群聊
服务器端:可以监测用户上线,离线,并实现消息转发功能
客户端:通过channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)
目的:进一步理解Netty非阻塞网络编程机制
Server
package com.lian.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.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 Server {
//监听端口
private Integer port;
public Server(Integer port) {
this.port = port;
}
//编写run方法,处理客户端的请求
public void run() throws InterruptedException {
//创建两个线程组
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//创建workerGroup启动类
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1280)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//向pipeline里加入解码器
pipeline.addLast("decoder",new StringDecoder());
向pipeline里加入编码器
pipeline.addLast("encoder",new StringEncoder());
向pipeline里加入自定义业务处理器
pipeline.addLast(new ServerHandler());
}
});
System.out.println("netty server start");
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
//监听关闭通道
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new Server(9999).run();
}
}
ServerHandler
package com.lian.groupchat;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ServerHandler extends SimpleChannelInboundHandler<String> {
/**
* 定义一个channle 组,管理所有的channel
* GlobalEventExecutor.INSTANCE) 是全局的事件执行器,是一个单例
*/
private static DefaultChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
/**
* handlerAdded 表示连接建立,一旦连接,第一个被执行
* 将当前channel 加入到 channelGroup
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
/**
* 将该客户加入聊天的信息推送给其它在线的客户端
* 该方法会将 channelGroup 中所有的channel 遍历,并发送 消息,
* 我们不需要自己遍历
*/
channelGroup.writeAndFlush("client: "+channel.remoteAddress()+" join chatting"+" time is "+sdf.format(new Date())+"\n");
channelGroup.add(channel);
}
/**
* 断开连接,将xx客户离开的消息推送给当前在线的其他客户,有人下线了通知到其他在线的人
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channelGroup.writeAndFlush("client "+channel.remoteAddress()+" leaving\n");
System.out.println("channelGroup size"+channelGroup.size());
}
/**
* 表示channel 处于活动状态, 提示 xx上线
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
System.out.println(channel.remoteAddress()+" on-line...");
}
/**
* 表示channel 处于不活动状态, 提示 xx离线了
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
System.out.println(channel.remoteAddress()+" off-line...");
}
/**
* 读取数据
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//获取当前通道
Channel channel = ctx.channel();
//循环遍历channelGroup组中的channel,
channelGroup.forEach(ch->{
//如果循环遍历的不是当前的channel,就转发消息给其他客户
if (channel != ch){
ch.writeAndFlush("client"+channel.remoteAddress()+" send message "+msg+"\n");
}else {
//如果循环遍历到的是当前channel,就回显自己发送的消息给自己
ch.writeAndFlush("self send message "+msg+"\n");
}
});
}
/**
* 捕获异常
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//出现异常关闭通道
ctx.channel().close();
}
}
client
package com.lian.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.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 Client {
private final String host;
private final Integer port;
public Client(String host, Integer port) {
this.host = host;
this.port = port;
}
public void run() throws Exception {
NioEventLoopGroup clientEventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(clientEventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder",new StringDecoder());
pipeline.addLast("encoder",new StringEncoder());
pipeline.addLast(new ClientHandler());
}
});
//绑定主机和端口
ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
Channel channel = channelFuture.channel();
System.out.println("----------"+channel.localAddress()+"-----------");
//创建扫描器
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
channel.writeAndFlush(msg+"\r\n");
}
//监听关闭通道
//channelFuture.channel().closeFuture().sync();
}finally {
clientEventLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new Client("127.0.0.1",9999).run();
}
}
ClientHandler
package com.lian.groupchat;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class ClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg.trim());
}
}
只针对某个客户端发送消息
问题
现在实现了客户端上下线及消息发送,所有客户端都可以收到,但是如果只想针对某个客户端发送消息怎么解决呢?
解决
//替代 DefaultChannelGroup ,可以用 List<Channel> 和 Map<String, Channel>
//使用一个 list 管理
public static List<Channel> channels = new ArrayList<Channel>();
//使用一个 hashmap 管理
public static Map<String, Channel> channels = new HashMap<String,Channel>();
还可以定义实体类、例如User类
public class User {
private int id;
private String pwd;
}
用User类作为key来指定客户端
public static Map<User, Channel> channels = new HashMap<String,Channel>();