[en] Support fastjson or protobuf-net

Topics: Technical Support
Nov 23, 2013 at 1:44 PM
Is it possible to add fastjson or protobuf-net? the BinaryFormatter is not good enough.
Nov 23, 2013 at 2:16 PM
I have find the way in ZyanConnection and ZyanComponentHost.
Coordinator
Nov 25, 2013 at 11:15 PM
Edited Nov 25, 2013 at 11:18 PM
Hi sky1248,

I haven't tried it myself because JSON and protobuf are both less capable than BinaryFormatter and don't meet the requirements of my projects, but you should be able to integrate any custom protocol using serialization handlers. Serialization handler is a class that implements ISerializationHandler interface:
public interface ISerializationHandler
{
    byte[] Serialize(object data);
    object Deserialize(Type dataType, byte[] data);
}
Serialization handlers are then registered on both sides of your connection in ZyanConnection.SerializationHandling (client-side) and ZyanComponentHost.SerializationHandling (server-side) as follows:
// client-side example
var connection = new ZyanConnection(serverUrl);

// list your types that you need to transfer using custom serializer
var types = new[] { typeof(MyClass1), typeof(MyClass2), ... }; 

// wrap your JSON or protobuf library by implementing ISerializationHandler interface
var serializationHandler = new MySerializer();

// register types for custom serialization
foreach (var type in types)
{
     connection.SerializationHandling[type] = serializationHandler;
}

// server-side — replace ZyanConnection with ZyanComponentHost
Another way of integrating a custom serialization protocol is using custom IFormatter implementation instead of binary formatter and injecting it into client/server sink chain. There is a working example of protobuf-based replacement of BinaryFormatter available here:

https://github.com/vadimskipin/Protobuf.Remoting

Integrating custom formatter is much trickier because it involves creating custom protocol setup classes. There is no help topic on the subject, so the easiest way of doing it is copying the source code of an existing protocol setup class pair (say, TcpDuplexClientProtocolSetup/TcpDuplexServerProtocolSetup), and tweaking it to meet your specific needs as follows:
// search for:
ClientSinkChain.Add(new BinaryClientFormatterSinkProvider(formatterSettings, null));
ServerSinkChain.Add(new BinaryServerFormatterSinkProvider(formatterSettings, null) { TypeFilterLevel = TypeFilterLevel.Full });

// to use protobuf formatter library, replace it with:
ClientSinkChain.Add(new ProtobufClientFormatterSinkProvider(formatterSettings, null));
ServerSinkChain.Add(new ProtobufServerFormatterSinkProvider(formatterSettings, null) { FallbackToBinaryFormatter = true });
Let me know if it helps.