尬聊聊天室第二版,第一版在这---->>>>第一版点我鸭
Netty编码解码器
解码器:负责处理"入站InboundHandler"数据
编码器:负责"出站OutboundHandler"数据
StringEncoder/StringDecoder 对字符串处理
ObjectEncoder/ObjectDecoder 对java对象处理
Netty的编解码器实现了ChannelHandlerAdapter,也是一种特殊的ChannelHandler,依赖于ChannelPipeline,可以将多个编解码器链接在一起,实现复杂的转换逻辑
代码如下
public class MyChatServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler())
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new MyChatServerInitializer());
try {
ChannelFuture future = serverBootstrap.bind(8899).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class MyChatServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyChatServerHandler());
}
}
public class MyChatServerHandler extends SimpleChannelInboundHandler {
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush("[服务器] - " + ctx.channel().remoteAddress() + "连接成功\r\n");
channelGroup.add(ctx.channel());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush("[服务器] - " + ctx.channel().remoteAddress() + "断开连接");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
Channel selfChannel = ctx.channel();
Iterator<Channel> iterator = channelGroup.iterator();
while (iterator.hasNext()) {
Channel channel = iterator.next();
if (selfChannel != channel) {
channel.writeAndFlush("[服务器] - " + selfChannel.remoteAddress()
+ "发送消息:" + msg + "\n");
continue;
}
String answer;
if (((String) msg).length() == 0) {
answer = "Please say something \r\n";
} else {
answer = "Did you say " + msg + " ?\r\n";
}
channel.writeAndFlush(answer);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.write("Welcome to server\r\n");
ctx.write("It is " + new Date() + " now.\r\n");
ctx.flush();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + "下线了");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
public class MyChatClient {
public static void main(String[] args) {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new MyChatClientInitializer());
try {
ChannelFuture future = bootstrap.connect("127.0.0.1", 8899).sync();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (; ; ) {
String msg = br.readLine();
future.channel().writeAndFlush(msg + "\r\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
}
public class MyChatClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyChatClientHandler());
}
}
public class MyChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
}
实现
1)运行服务端
2)运行客户端44
3)运行客户端30
4)客户端下线