这篇博客主要读述使用netty实现简单的聊天室功能 ,当然真正的聊天功能绝对不会这么简单,说简单只是相对于JDK原生的NIO模型来说。理解这个demo你需要对NIO和Netty的流程有一定的了解。推荐可以去看一下《Scalable IO in JAVA》
话不多说,来看代码
Server端代码
package com.patrick.netty.chat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
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 io.netty.util.CharsetUtil;
public class ChatServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
try {
bootstrap.group(bossGroup , workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG , 1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast("encoder",new StringEncoder(CharsetUtil.UTF_8))
.addLast("decoder",new StringDecoder(CharsetUtil.UTF_8))
.addLast(new ChatServerHandler());
}
});
System.out.println("---------聊天室服务器已启动-------------");
ChannelFuture cf = bootstrap.bind(9000).sync();
cf.channel().closeFuture().sync();
} catch (Exception e){
e.printStackTrace();
}finally {
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
package com.patrick.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;
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
private static ChannelGroup defaultChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
Channel connectChannel = channelHandlerContext.channel();
for (Channel defaultChannel : defaultChannels) {
if (defaultChannel !=connectChannel) {
defaultChannel.writeAndFlush("客户端"+connectChannel.remoteAddress()+"发送信息:"+msg);
}else{
defaultChannel.writeAndFlush("服务端"+connectChannel.remoteAddress()+"通知:"+msg);
}
}
System.out.println("客户端" + connectChannel.remoteAddress() + "发送信息:" + msg);
}
/**
* 监听客户端连接情况
* @param ctx
* @throws Exception
*/
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channel.writeAndFlush("客户端"+channel.remoteAddress()+"已上线");
defaultChannels.add(channel);
System.out.println("客户端"+channel.remoteAddress()+"已上线");
//向所有客户端通知上线信息
for (Channel defaultChannel : defaultChannels) {
if (defaultChannel !=channel) {
defaultChannel.writeAndFlush("客户端"+channel.remoteAddress()+"已上线");
}
}
}
/**
* 监听客户端断开情况
* @param ctx
* @throws Exception
*/
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channel.writeAndFlush("客户端"+channel.remoteAddress()+"下线了");
System.out.println("客户端"+channel.remoteAddress()+"下线了");
}
/**
* 异常处理
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.fireExceptionCaught(cause);
}
}
Client端
package com.patrick.netty.chat;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
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 io.netty.util.CharsetUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ChatClient {
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group) //设置线程组
.channel(NioSocketChannel.class) //采用NioSocketChannel作为客户端连接通道
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8))
.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8))
.addLast(new ChatClientHandler());
}
});
System.out.println("------客户端已启动------");
ChannelFuture channelFuture = bootstrap.connect("localhost", 9000).sync();
//获取channel
Channel channel = channelFuture.channel();
//往channel中写数据
for (; true; ) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
channel.writeAndFlush(bufferedReader.readLine() + "\r\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
}
package com.patrick.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 msg) throws Exception {
System.out.println(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}