我正在尝试创建一个标准化的事件消息系统(用于我的游戏服务器和客户端),该系统使用protobuf网络通过UDP套接字发送数据,以实现快速和最佳的数据传输。
目前,我正在尝试发送一个事件类,它可能是PlayerIntentEvent
类,也可能是OnConnectionEvent
类(存在更多的事件,这些只是一个例子)。
我正在发送一个字节[],其中第一个字节表示事件类(用于取消序列化),其余字节[]是类本身,用protobuf-net序列化。这部分工作正常。我的问题在接收部分我想基于类型变量动态反序列化一个类
经过一周的探索和尝试,我找不到一种方法来做到这一点。
我的当前设置:
事件类型的常量:
public static class EventTypes {
public static byte OnConnection = 1;
public static byte OnError = 2;
public static byte OnPlayerIntent = 3;
}
服务器的事件映射:
public static class Constants {
public static Dictionary<byte, Type> EventDataCastDictionary = new Dictionary<byte, Type> {
{ EventTypes.OnConnection, null },
{ EventTypes.OnPlayerIntent, typeof (PlayerIntentEvent) }
};
public static readonly IPEndPoint ClientEndPoint = new IPEndPoint(IPAddress.Any, 0);
public static readonly IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Any, 9423);
}
出于测试目的,我创建了一个sender方法,该方法只将PlayerIntentEvent发送到服务器:
public void SendPlayerIntent(PlayerIntentEvent packet) {
try {
byte[] bytes;
using (MemoryStream stream = new MemoryStream()) {
stream.WriteByte(EventTypes.OnPlayerIntent);
ProtoBuf.Serializer.Serialize<PlayerIntentEvent>(stream, packet);
bytes = stream.ToArray();
}
//client is an instance of UdpClient
client.Send(bytes, bytes.Length, serverEndPoint);
} catch (Exception err) {
throw err;
}
}
我的服务器的接收端:
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;
using ProtoBuf;
abstract class UdpBase {
protected UdpClient Client;
protected UdpBase() {
Client = new UdpClient();
}
public async Task<Received> Receive() {
var receivedStream = await Client.ReceiveAsync();
NetworkPacket networkPacket = new NetworkPacket();
object packet = null;
//Getting the class type from the first byte of the array
Type eventType = Constants.EventDataCastDictionary[receivedStream.Buffer[0]];
//----PROBLEM
//Here I am reading only the class
using (var stream = new MemoryStream(receivedStream.Buffer, 1, receivedStream.Buffer.Length - 1)) {
//I want to put a type from my mapping in place of the ?????*
//I have tried using eventType variable, but the code does not compile
packet = Serializer.Deserialize<?????*>(stream);
}
//----END OF PROBLEM
//The return statement is not finished
return new Received();
}
}
更新:
在使用大卫的修改后,我已经开始接收
Exception thrown: 'ProtoBuf.ProtoException' in protobuf-net.dll
Exception thrown: 'ProtoBuf.ProtoException' in mscorlib.dll
更新2:
我的事件类缺少一个默认的无参数构造函数。现在一切都在工作,即使没有Convert.ChangeType
。:)
您可以使用非泛型重载并强制转换结果:
Type eventType = Constants.EventDataCastDictionary[receivedStream.Buffer[0]];
using (var stream = new MemoryStream(receivedStream.Buffer, 1,
receivedStream.Buffer.Length - 1)) {
packet = Convert.ChangeType(Serializer.Deserialize(eventType, stream),
eventType);
}