0%

Netty-PipLine

文章字数:233,阅读全文大约需要1分钟

pipLine是Netty数据链式处理的处理流,每一个节点都能处理数据并返回传入值类型的对象,再给下一个节点。一般来说会使用一些工具类对于数据现行处理,然后再进入自身的数据处理中。

字符串类型粘包和拆包

使用LineBasedFrameDecoder和StringDecoder处理之后的msg

1
2
3
4
5
6
7
8
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
arg0.pipeline().addLast(new StringDecoder());
arg0.pipeline().addLast(new NettyServerHandler());
}
}

请求中的字符串会被\n或者\r分割成一个个部分,分别被channelRead执行。一次连接中多次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 接收客户端消息,自动触发
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String mess = (String) msg;
System.out.println("服务端收到 = " + mess);
//回复消息
String respMess = message+"\n";
ByteBuf respByteBuf = Unpooled.copiedBuffer(respMess.getBytes());
ctx.write(respByteBuf);
}

http解析

1
2
3
4
//request解码
arg0.pipeline().addLast(new HttpRequestDecoder());
//request解码
arg0.pipeline().addLast(new HttpRequestDecoder());