也许你已经想通了,但是对于其他在这里找到这个的人(比如我)。这是答案。
该错误消息告诉您,您必须定义一个序列化程序。您有一个要发送的对象,但您没有告诉 NetworkComms 使用什么序列化程序。因此,您可以在对象中实现 IExplicitlySerialize,也可以使用已经为 protobuf-net 创建的序列化程序。
您需要使用NetworkCommsDotNet.DPSBase.ProtobufSerializer。您必须引用从您可以在 github 上获得的 NetworkComms 源编译的 ProtobufSerializer.dll,然后定义 SendReceiveOptions。
例子:
SendReceiveOptions customSendReceiveOptions = new SendReceiveOptions<ProtobufSerializer>();
ConnectionInfo connectionInfo = new ConnectionInfo("192.168.1.105", 5614);
TCPConnection serverConnection = TCPConnection.GetConnection(connectionInfo, customSendReceiveOptions);
var message = "This is a test packet";
serverConnection.SendObject("PacketPrintToConsole", new PacketPrintToConsole(message));
这只需要在对象将被序列化以发送的地方进行。接收客户端只需要具有具有相同对象类的 protobuf-net 即可反序列化。
使用 SendReceiveObject 请求消息的示例。
SendReceiveOptions customSendReceiveOptions = new SendReceiveOptions<ProtobufSerializer>();
NetworkComms.AppendGlobalIncomingPacketHandler<int>("GetMessage", GetMessageRequest, customSendReceiveOptions);
发送结果的方法:
private static void GetMessageRequest(PacketHeader packetheader, Connection connection, int incomingobject)
{
connection.SendObject("MessageReply", new MessageObject(message));
}
然后在客户端:
ConnectionInfo connectionInfo = new ConnectionInfo("192.168.2.105", 5614);
TCPConnection serverConnection = TCPConnection.GetConnection(connectionInfo);
MessageObject myMessageObject = serverConnection.SendReceiveObject<ImageWrap>("GetMessage", "MessageReply", 1000);
if (myMessageObject != null)
{
Console.WriteLine(myMessageObject.Message);
}