48 lines
1.3 KiB
C#
48 lines
1.3 KiB
C#
using System;
|
|
|
|
namespace XWorld.Framework.Protocol
|
|
{
|
|
public enum Channel : byte
|
|
{
|
|
Framework = 0, // 匹配/心跳/大厅等框架消息
|
|
Game = 1, // 转发给具体小游戏房间的业务消息
|
|
}
|
|
|
|
// 一帧线网消息
|
|
public readonly struct Frame
|
|
{
|
|
public readonly Channel Channel;
|
|
public readonly ushort Opcode;
|
|
public readonly byte[] Payload;
|
|
|
|
public Frame(Channel channel, ushort opcode, byte[] payload)
|
|
{
|
|
Channel = channel;
|
|
Opcode = opcode;
|
|
Payload = payload ?? Array.Empty<byte>();
|
|
}
|
|
}
|
|
|
|
public static class FrameCodec
|
|
{
|
|
// 线网: [channel:u8][opcode:u16 LE][payloadLen:varuint][payload]
|
|
public static byte[] Encode(Frame frame)
|
|
{
|
|
var w = new PacketWriter(frame.Payload.Length + 8);
|
|
w.WriteByte((byte)frame.Channel);
|
|
w.WriteUInt16(frame.Opcode);
|
|
w.WriteBytes(frame.Payload); // 自带 varuint 长度前缀
|
|
return w.ToArray();
|
|
}
|
|
|
|
public static Frame Decode(byte[] data)
|
|
{
|
|
var r = new PacketReader(data);
|
|
var channel = (Channel)r.ReadByte();
|
|
ushort opcode = r.ReadUInt16();
|
|
byte[] payload = r.ReadBytes();
|
|
return new Frame(channel, opcode, payload);
|
|
}
|
|
}
|
|
}
|