我們在使用網絡編程時,可以根據自己的業務場景,設計自己的協議。比如我們與外部接口對接,會使用一定特定的加密算法,使用特定的標籤,以及固定格式的報文等等,都可以算作我們確定身份的協議。
下面我們設計一個自己的協議,來實現一些功能。
一、協議要素
創建一個好的協議,通常來說,必然要有以下要素:
- 魔數:用來在第一時間判定是否是無效數據包
- 例如:Java Class文件都是以0x CAFEBABE開頭的。Java這麼做的原因就是爲了快速判斷一個文件是不是有可能爲class文件,以及這個class文件有沒有受損。
- 版本號:可以支持協議的升級
- 序列化算法:消息正文到底採用哪種序列化反序列化方式
- 指令類型:針對業務類型指定
- 請求序號:爲了雙工通信,提供異步能力,序號用於回調
- 正文長度:沒有長度會導致瀏覽器持續加載
- 消息正文:具體消息內容
二、自定義編解碼器
我們下面簡單的寫一個自定義編解碼器,主要是爲了體驗過程,深刻印象。
在寫這個之前,先歇一歇準備工作;我們需要準備一個父類Message:
import lombok.Data;
import java.io.Serializable;
@Data
public abstract class Message implements Serializable {
public final static int LOGIN_REQUEST_MESSAGE = 0;
private int messageType;
private int sequenceId;
abstract int getMessageType();
}
一個子類LoginMessage:
@Data
public class LoginMessage extends Message {
private String username;
private String password;
private Date loginTime;
public LoginMessage(String username, String password, Date loginTime) {
this.username = username;
this.password = password;
this.loginTime = loginTime;
}
@Override
int getMessageType() {
return LOGIN_REQUEST_MESSAGE;
}
}
有了以上的基礎,我們就能編寫編解碼器了,按照前面提到的幾個要素,按照順序逐一編寫:
public class MessageCodec extends ByteToMessageCodec<Message> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Message msg, ByteBuf out) throws Exception {
// 4 字節的魔數
out.writeBytes(new byte[]{1, 2, 3, 4});
// 1 字節的版本,
out.writeByte(1);
// 1 字節的序列化方式 0:jdk
out.writeByte(0);
// 1 字節的指令類型
out.writeByte(msg.getMessageType());
// 4 個字節的請求序號
out.writeInt(msg.getSequenceId());
// 無意義,對齊填充,使其滿足2的n次方
out.writeByte(0xff);
// 獲取內容的字節數組
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(msg);
byte[] bytes = bos.toByteArray();
// 長度
out.writeInt(bytes.length);
// 寫入內容
out.writeBytes(bytes);
}
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
int magicNum = in.readInt();
byte version = in.readByte();
byte serializerType = in.readByte();
byte messageType = in.readByte();
int sequenceId = in.readInt();
in.readByte();
int length = in.readInt();
byte[] bytes = new byte[length];
in.readBytes(bytes, 0, length);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
Message message = (Message) ois.readObject();
System.out.println("decode:" + magicNum + "," + version + "," + serializerType + "," + messageType + "," + sequenceId + "," + length);
System.out.println("decode:" + message);
out.add(message);
}
}
下面寫個客戶端,用於發送消息:
public class Client {
public static void main(String[] args) {
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
bootstrap.group(worker);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
//引入我們的編解碼器
ch.pipeline().addLast(new MessageCodec());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//組裝消息,併發送
Message message = new LoginMessage("Tom","123456",new Date());
ctx.writeAndFlush(message);
super.channelActive(ctx);
}
});
}
});
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",8080);
//阻塞等待連接
channelFuture.sync();
//阻塞等待釋放連接
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("server error:" + e);
} finally {
// 釋放EventLoopGroup
worker.shutdownGracefully();
}
}
}
下面是服務端,用於接收消息和解碼:
public class Server {
public static void main(String[] args) {
NioEventLoopGroup boss = new NioEventLoopGroup(1);
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.group(boss, worker);
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
//引入編解碼器
ch.pipeline().addLast(new MessageCodec());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//打印消息內容
System.out.println(msg);
super.channelRead(ctx, msg);
}
});
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8080);
//阻塞等待連接
channelFuture.sync();
//阻塞等待釋放連接
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("server error:" + e);
} finally {
// 釋放EventLoopGroup
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
結果:
decode:16909060,1,0,0,0,326
decode:LoginMessage(username=Tom, password=123456, loginTime=Tue Nov 16 15:47:06 CST 2021)
LoginMessage(username=Tom, password=123456, loginTime=Tue Nov 16 15:47:06 CST 2021)
上面前兩條是我們在編解碼器中打印的日誌,最後一條是我們的業務代碼打印。
16909060表示我們的魔數,這裏是10進製表示的,轉化成二進制其實是[01 02 03 04],後面的數字都是我們根據要素指定的。
而326使我們發送消息的字節長度。
存在的問題?
其實在我們的代碼當中存在問題,我們對整個請求都設置了自己的協議,會有以下兩種情況:
1)粘包,這種情況下,我們可以根據自己的規則獲取到正確的消息,因爲消息內容的長度等等都有指定。
2)半包,此時將導致我們的消息獲取不完全,解碼失敗。
所以我們仍然要使用前一章節當中的解碼器:
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,12,4,0,0));
參數解釋分別是最大長度1024,消息長度偏移量12,消息長度4,消息長度距離消息0個長度,需要從頭部剝離0個長度。