Netty入门 : 实现简易聊天室
- 准备工作: 添加依赖包(JDK版本 8 以上)
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.55.Final</version>
</dependency>
- server端代码
package netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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;
import java.util.Scanner;
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
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());
pipeline.addLast(new NettyServerHandler());
}
});
System.out.println("Netty server start ...");
ChannelFuture cf = bootstrap.bind(9000).sync();
cf.addListener(cd->{
if(cd.isSuccess()){
System.out.println("success");
}else{
System.out.println("failed");
}
});
Scanner scanner = new Scanner(System.in); // 服务端给客户端发信息
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
NettyServerHandler.sendAll(msg);
//cf.channel().writeAndFlush(msg);
}
cf.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
- 客户端代码
package netty;
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 NettyClient {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("decoder",new StringDecoder());
pipeline.addLast("encoder",new StringEncoder());
pipeline.addLast(new NettyClientHandler());
}
});
System.out.println( " netty client start ");
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",9000).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);
}
channelFuture.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
- 服务端handler
package netty;
import io.netty.channel.*;
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 NettyServerHandler extends SimpleChannelInboundHandler<String> {
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Channel channel = ctx.channel();
System.out.println(channel.remoteAddress()+" == " +msg);
channelGroup.forEach(ch->{
if (channel!=ch) {
ch.writeAndFlush("[ ke hu duan ]" + channel.remoteAddress() + "发送了消息 : " + msg + "\n");
}else{
ch.writeAndFlush("[ self ] 发送了消息: " + msg + "\n");
}
});
}
public static void sendAll(String msg){ // 自己琢磨添加的 用于服务端发信息给所有客户端 目前不知是否有问题
channelGroup.forEach(channel -> {
channel.writeAndFlush("服务的公告: "+msg+"\n");
});
}
public void channelActive(ChannelHandlerContext ctx){
Channel channel = ctx.channel();
channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+" 上线了 "+sf.format(new Date())+"\n");
channelGroup.add(channel);
System.out.println(ctx.channel().remoteAddress()+" 上线了" + "\n");
}
public void channelInactive(ChannelHandlerContext ctx) {
Channel channel = ctx.channel();
channelGroup.writeAndFlush("[ 客户端 ] " +channel.remoteAddress()+ " 下线了"+"\n");
System.out.println(channel.remoteAddress()+" 下线了.\n");
System.out.println("channelGroup size = "+ channelGroup.size());
}
}
- 客户端handler
package netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
System.out.println(msg.trim());
}
}
运行结果:
客户端发消息: