基于Netty的简单聊天室的实现
可以先看一下效果截图:
首先服务端启动,随之启动三个客户端:
其中,客户端2发送消息:I am monkeyhlj
客户端1和客户端3分别接收到客户端2的消息:
之后,客户端2和3分别下线:
客户端1下线:
Demo的代码如下:
所需依赖:
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.69.Final</version>
</dependency>
</dependencies>
ChatClient:
package com.monkey.netty.chat;
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;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.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());
//加入自己的业务处理handler
pipeline.addLast(new ChatClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",9000).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);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
package com.monkey.netty.chat;
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.trim());
}
}
ChatServer:
package com.monkey.netty.chat;
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;
public class ChatServer {
public static void main(String[] args) throws Exception{
//创建两个线程组bossGroup和workerGroup,含有的了线程NioEventLoop的个数默认为cpu核数的两倍
//bossGroup只是处理连接请求,真 正的和客户端业务处理,会交给workerGroup完成
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(8);
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1024)
.childHandler(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());
//加入自己的业务处理handler
pipeline.addLast(new ChatServerHandler());
}
});
System.out.println("聊天室Server启动。。。");
ChannelFuture channelFuture = bootstrap.bind(9000).sync();
//关闭通道
channelFuture.channel().closeFuture().sync();
}catch (Exception e){
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
package com.monkey.netty.chat;
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 ChatServerHandler extends SimpleChannelInboundHandler<String>{
//GlobalEventExecutor.INSTANCE 是全局的事件执行器,是一个单例
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//表示channel处于就绪状态,提示上线
@Override
public void channelActive(ChannelHandlerContext ctx){
Channel channel = ctx.channel();
//将该客户加入聊天的信息推送给其他在线的客户端
//该方法会将channelGroup中所有的channel遍历,并发送消息
channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "上线了" + sdf.format(new Date()) + "\n");
//将当前channel加入到channelGroup
channelGroup.add(channel);
System.out.println(ctx.channel().remoteAddress()+"上线了"+"\n");
}
//表示channel处于不活动状态,提示离线了
@Override
public void channelInactive(ChannelHandlerContext ctx){
Channel channel = ctx.channel();
//将该客户离开信息推送给“当前在线的用户”
channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "下线了" + "\n");
System.out.println(ctx.channel().remoteAddress()+"下线了"+"\n");
System.out.println("channelGroup size="+channelGroup.size());
}
//读取数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//获取到当前channel
Channel channel = ctx.channel();
//这时我们遍历channelGroup,根据不同的情况,回送不同的消息
channelGroup.forEach(ch -> {
if(channel != ch){ //不是当前的channel,转发消息
ch.writeAndFlush("[ 客户端 ]"+channel.remoteAddress()+"发送了消息:"+msg+"\n");
}else{ //回显自己发送的消息给自己
ch.writeAndFlush("[自己]发送了消息:"+msg);
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
//关闭通道
ctx.close();
}
}
【参考】netty官网:https://netty.io/index.html
【maven依赖查找】注:原来的那个好像现在不能用了,发现了一个新的:http://mvn.coderead.cn/
【参考】https://www.bilibili.com/video/BV1Am4y1f7Ec?p=11