關鍵字: Netty簡介,Netty實現通信的步驟,綁定多個端口,TCP粘包、拆包問題,DellmiterBasedFrameDecoder(自定義分隔符), FixedLengthFrameDecoder(定長)
代碼在 https://github.com/zhaikaishun/NettyTutorial 下的socketIO02
Netty簡介
Netty是一個高性能、異步事件驅動的NIO框架,它提供了對TCP、UDP和文件傳輸的支持,作爲一個異步NIO框架,Netty的所有IO操作都是異步非阻塞的,通過Future-Listener機制,用戶可以方便的主動獲取或者通過通知機制獲得IO操作結果。
作爲當前最流行的NIO框架,Netty在互聯網領域、大數據分佈式計算領域、遊戲行業、通信行業等獲得了廣泛的應用,一些業界著名的開源組件也基於Netty的NIO框架構建。
Netty架構組成
http://incdn1.b0.upaiyun.com/2015/04/28c8edde3d61a0411511d3b1866f0636.png
代碼在SocketIO_02
Netty實現通信的步驟
服務器端
1. 創建兩個的NIO線程組, 一個專門用於網絡事件處理(接受客戶端的連接),另一個則進行網絡通信讀寫
創建一個ServerBootstrap對象,配置Netty的一系列參數,例如接受傳出數據的緩存大小等等。
創建一個實際處理數據的類Channellnitializer,進行初始化的準備工作,比如設置傳出數據的字符集、格式、已經處理數據的接口
- 綁定端口,執行同步阻塞方法等待服務器端啓動即可。
第一個Netty的例子
Server端
public class Server {
public static void main(String[] args) throws Exception {
//1 創建線兩個程組
//一個是用於處理服務器端接收客戶端連接的
//一個是進行網絡通信的(網絡讀寫的)
EventLoopGroup pGroup = new NioEventLoopGroup();
EventLoopGroup cGroup = new NioEventLoopGroup();
//2 創建輔助工具類,用於服務器通道的一系列配置
ServerBootstrap b = new ServerBootstrap();
b.group(pGroup, cGroup) //綁定倆個線程組
.channel(NioServerSocketChannel.class) //指定NIO的模式
.option(ChannelOption.SO_BACKLOG, 1024) //設置tcp緩衝區
.option(ChannelOption.SO_SNDBUF, 32*1024) //設置發送緩衝大小
.option(ChannelOption.SO_RCVBUF, 32*1024) //這是接收緩衝大小
.option(ChannelOption.SO_KEEPALIVE, true) //保持連接
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
//3 在這裏配置具體數據接收方法的處理
sc.pipeline().addLast(new ServerHandler());
}
});
//4 進行綁定
ChannelFuture cf1 = b.bind(8765).sync();
//ChannelFuture cf2 = b.bind(8764).sync();
//5 等待關閉
cf1.channel().closeFuture().sync();
//cf2.channel().closeFuture().sync();
pGroup.shutdownGracefully();
cGroup.shutdownGracefully();
}
}
ServerHandler
public class ServerHandler extends ChannelHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("server channel active... ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "utf-8");
System.out.println("Server :" + body );
String response = "進行返回給客戶端的響應:" + body ;
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
//.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx)
throws Exception {
System.out.println("讀完了");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t)
throws Exception {
ctx.close();
}
}
Client端
public class Client {
public static void main(String[] args) throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture cf1 = b.connect("127.0.0.1", 8765).sync();
//ChannelFuture cf2 = b.connect("127.0.0.1", 8764).sync();
//發送消息
Thread.sleep(1000);
cf1.channel().writeAndFlush(Unpooled.copiedBuffer("777".getBytes()));
cf1.channel().writeAndFlush(Unpooled.copiedBuffer("666".getBytes()));
//cf2.channel().writeAndFlush(Unpooled.copiedBuffer("888".getBytes()));
Thread.sleep(2000);
cf1.channel().writeAndFlush(Unpooled.copiedBuffer("888".getBytes()));
//cf2.channel().writeAndFlush(Unpooled.copiedBuffer("666".getBytes()));
cf1.channel().closeFuture().sync();
//cf2.channel().closeFuture().sync();
group.shutdownGracefully();
}
}
ClientHandle
public class ClientHandler extends ChannelHandlerAdapter{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "utf-8");
System.out.println("Client :" + body );
String response = "收到服務器端的返回信息:" + body;
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
}
}
先運行Server, 再運行Client
Server端輸出
server channel active...
Server :777666
讀完了
Server :888
讀完了
Client端輸出
Client :進行返回給客戶端的響應:777666
Client :進行返回給客戶端的響應:888
例子解讀:
Server端是不停的監聽Client端的消息, Client和Server端的連接是不會停止的,如果想要在Client和Server之間通線後停止Client和Server端的連接,在ServerHandler的channelRead中加上addListener(ChannelFutureListener.CLOSE),然後在Client端添加cf1.channel().closeFuture().sync(); group.shutdownGracefully(); 就是Client也在異步的監聽,如果消息完成,就close掉連接
例如上面那個例子
ServerHandle處
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes())).addListener(ChannelFutureListener.CLOSE)
Client處添加
cf1.channel().closeFuture().sync();
group.shutdownGracefully();
這樣的話,在Client端通信一次之後就斷開了,也就是Server只能收到777666的信息,888的信息是接收不到的。
注意: 這個異步關閉,一定要在Server端進行關閉,不要在Client端關閉。
如果不想關閉,想保持長連接,那就不加上面那一些代碼即可
綁定多個端口
例如上面那個例子,希望再加一個端口
Server端加上
ChannelFuture cf2 = b.bind(8764).sync();
cf2.channel().closeFuture().sync();
Client端
ChannelFuture cf2 = b.connect("127.0.0.1", 8764).sync();
cf2.channel().closeFuture().sync();
TCP粘包、拆包問題
熟悉tcp編程的可能知道,無論是服務端還是客戶端,當我們讀取或者發送數據的時候,都需要考慮TCP底層的粘包個拆包機制。
tcp是一個“流”協議,所謂流就是沒有界限的傳輸數據,在業務上,一個完整的包可能會被TCP分成多個包進行發送,也可能把多個小包封裝成一個大的數據包發送出去,這就是所謂的tcp粘包、拆包問題。
分析TCP粘包拆包問題的產生原因:
1. 應用程序write寫入的字節大於套接口緩衝區的大小
2. 進行mss大小的TCP分段
3. 以太網的payload大於MTU進行IP分片
粘包拆包問題,根據業界主流協議,有三種主要方案:
1. 消息定長,例如每個報文的大小固定200個字節,如果不夠,空位補空格
2. 在包尾部增加特殊字符進行分割,例如加回車等
3. 將消息分爲消息頭和消息體,在消息頭中包含表示消息總長度的字段,然後進行業務邏輯的處理。
TCP粘包拆包之分隔符類 DellmiterBasedFrameDecoder(自定義分隔符)
代碼在bhz.netty.ende1下
Server端
public class Server {
public static void main(String[] args) throws Exception{
//1 創建2個線程,一個是負責接收客戶端的連接。一個是負責進行數據傳輸的
EventLoopGroup pGroup = new NioEventLoopGroup();
EventLoopGroup cGroup = new NioEventLoopGroup();
//2 創建服務器輔助類
ServerBootstrap b = new ServerBootstrap();
b.group(pGroup, cGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.option(ChannelOption.SO_SNDBUF, 32*1024)
.option(ChannelOption.SO_RCVBUF, 32*1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
//設置特殊分隔符
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
//設置字符串形式的解碼
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new ServerHandler());
}
});
//4 綁定連接
ChannelFuture cf = b.bind(8765).sync();
//等待服務器監聽端口關閉
cf.channel().closeFuture().sync();
pGroup.shutdownGracefully();
cGroup.shutdownGracefully();
}
}
ServerHandle端
public class ServerHandler extends ChannelHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(" server channel active... ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String request = (String)msg;
System.out.println("Server :" + msg);
String response = "服務器響應:" + msg + "$_";
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {
ctx.close();
}
}
Client端
public class Client {
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
//
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();
cf.channel().writeAndFlush(Unpooled.wrappedBuffer("bbbb$_".getBytes()));
cf.channel().writeAndFlush(Unpooled.wrappedBuffer("cccc$_".getBytes()));
//等待客戶端端口關閉
cf.channel().closeFuture().sync();
group.shutdownGracefully();
}
}
ClientHandle端
public class ClientHandler extends ChannelHandlerAdapter{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client channel active... ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
String response = (String)msg;
System.out.println("Client: " + response);
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
先啓動Server端,再啓動Client端
Client端輸出
client channel active...
Client: 服務器響應:bbbb
Client: 服務器響應:cccc
Server端輸出
server channel active...
Server :bbbb
Server :cccc
TCP粘包拆包之FixedLengthFrameDecoder(定長)
和上面的代碼類似
Server端
public class Server {
public static void main(String[] args) throws Exception{
//1 創建2個線程,一個是負責接收客戶端的連接。一個是負責進行數據傳輸的
EventLoopGroup pGroup = new NioEventLoopGroup();
EventLoopGroup cGroup = new NioEventLoopGroup();
//2 創建服務器輔助類
ServerBootstrap b = new ServerBootstrap();
b.group(pGroup, cGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.option(ChannelOption.SO_SNDBUF, 32*1024)
.option(ChannelOption.SO_RCVBUF, 32*1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
//設置定長字符串接收
sc.pipeline().addLast(new FixedLengthFrameDecoder(5));
//設置字符串形式的解碼
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new ServerHandler());
}
});
//4 綁定連接
ChannelFuture cf = b.bind(8765).sync();
//等待服務器監聽端口關閉
cf.channel().closeFuture().sync();
pGroup.shutdownGracefully();
cGroup.shutdownGracefully();
}
}
ServerHandler
public class ServerHandler extends ChannelHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(" server channel active... ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String request = (String)msg;
System.out.println("Server :" + msg);
String response = request ;
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {
}
}
Client
public class Client {
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new FixedLengthFrameDecoder(5));
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();
cf.channel().writeAndFlush(Unpooled.wrappedBuffer("aaaaabbbbb".getBytes()));
cf.channel().writeAndFlush(Unpooled.copiedBuffer("ccccccc".getBytes()));
//等待客戶端端口關閉
cf.channel().closeFuture().sync();
group.shutdownGracefully();
}
}
ClientHandler
public class ClientHandler extends ChannelHandlerAdapter{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client channel active... ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String response = (String)msg;
System.out.println("Client: " + response);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
}
}
先運行Server端,再運行Client端
Client端輸出
client channel active...
Client: aaaaa
Client: bbbbb
Client: ccccc
Server端輸出
server channel active...
Server :aaaaa
Server :bbbbb
Server :ccccc
可以看到,每次定長都是5個字符, 有兩個cc,由於不夠五個,導致丟掉了
自定義協議粘包拆包
使用消息頭和消息體, 暫未記錄筆記。 TODO zhaikaishun
特別感謝互聯網架構師白鶴翔老師,本文大多出自他的視頻講解。
筆者主要是記錄筆記,以便之後翻閱,正所謂好記性不如爛筆頭,爛筆頭不如雲筆記