背景知识
本系列内容主要讲解一下较为底层的netty通信,通过一些例子和基础知识点来讲解。
接收端
package test;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.io.*;
/**
* Created by jianghuiwen on 17/8/20.
*/
public class TestServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("请求来啦!");
ByteBuf buf = (ByteBuf)msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req,"GBK");
System.out.println("本次接收长度="+body.length()+",接收中..."+body);
return;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
写入是直接采用telnet命令写入字符串。
在通道里发送的数据,都是byte数组,其中telnet回车即表示flush将字符串写入到通道并且发送出去。
服务端在默认情况下,接收到的是ByteBuf对象,该对象是一个字符串缓冲,所有从客户端发送过来的数据都会缓存在该缓冲队列中。至于什么时候server的handler会取出字符,取决于队列的长度。
handler读取完ByteBuf后,就会将缓存队列的指针后移,等待新的数据写入。