netmq4.0.0.207 二进制序列化及反序列化,支持中文。
代码参考网络上的。
namespace Console452
{
[Serializable]
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime BirthDay { set; get; }
public Address Address { get; set; }
}
[Serializable]
public class Address
{
public string Line1 { get; set; }
public string Line2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"{ NetMQ.NetMQConfig.ThreadPoolSize},{ NetMQ.NetMQConfig.MaxSockets}");
using (var server = new ResponseSocket("tcp://localhost:5556")) // bind
using (var client = new RequestSocket("tcp://localhost:5556")) // connect
{
// Send a message from the client socket
var person = new Person
{
Id = 123,
Name = "First",
BirthDay = DateTime.Parse("1980-11-15"),
Address = new Address { Line1 = "中国", Line2 = "Line2" }
};
using (var sm = new MemoryStream())
{
//Serializer.PrepareSerializer<Person>();
//Serializer.Serialize(sm, person);
//sender.Send(sm.ToArray());
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(sm, person);
client.SendFrame(sm.ToArray());
}
//client.SendFrame("Hello");
// Receive the message from the server socket
var receivedBytes = server.ReceiveFrameBytes();
using (var sm = new MemoryStream(receivedBytes))
{
//Protobuf.net 序列化在多线程方式下报错:
/*
Timeout while inspecting metadata; this may indicate a deadlock.
This can often be avoided by preparing necessary serializers during application initialization,
rather than allowing multiple threads to perform the initial metadata inspection;
please also see the LockContended event
*/
//var person = Serializer.Deserialize<Person>(sm);
//采用二进制方式
var binaryFormatter = new BinaryFormatter();
var person2 = binaryFormatter.Deserialize(sm) as Person;
Console.WriteLine("Person {Id:" + person.Id + ",Name:" + person.Name + ",BirthDay:" +
person.BirthDay + ",Address:{Line1:" + person.Address.Line1 +
",Line2:" + person.Address.Line2 + "}}");
Console.WriteLine("Sending to Sink:" + person.Id);
}
// Send a response back from the server
server.SendFrame("Hi Back");
// Receive the response from the client socket
string m2 = client.ReceiveFrameString();
Console.WriteLine("From Server: {0}", m2);
Console.Read();
client.SendFrame("Hello333");
}
}
}
}