msgpack可以使用C#打包用户定义的对象,然后将其发送到C应用程序,然后在其中解压缩吗?
作者:互联网
我有一个C#回复服务器,可以打包一个对象并将其发送到请求者C#客户端.我可以做同样的事情,但是使用C#答复服务器与C请求者客户端进行通信吗?
这是我的C#回复服务器的示例:
using System;
using System.Text;
using ZMQ;
using MsgPack;
namespace zmqMpRep
{
public class Weather
{
public int zipcode;
public int temperature;
public int humidity;
}
public class zmqMpRep
{
public static void Main(string[] args)
{
Socket replier = new Socket( SocketType.REP );
replier.Bind( "tcp://127.0.0.1:9293" );
while( true ) {
Weather weather = new Weather { zipcode = 60645, temperature = 67, humidity = 50 };
CompiledPacker packer = new CompiledPacker( false );
byte[] packWeather = packer.Pack<Weather> ( weather );
string request = replier.Recv(Encoding.Unicode);
Console.WriteLine( request.ToString() );
replier.Send( packWeather );
Weather test = packer.Unpack<Weather>( packWeather );
Console.WriteLine( "The temp of zip {0} is {1}", test.zipcode, test.temperature );
}
}
}
}
这是我的C#请求客户端:
using System;
using System.Text;
using ZMQ;
using MsgPack;
namespace zmqMpReq
{
public class Weather
{
public int zipcode;
public int temperature;
public int humidity;
}
public class zmqMpReq
{
public static void Main(string[] args)
{
CompiledPacker packer = new CompiledPacker( false );
Socket requester = new Socket( SocketType.REQ );
requester.Connect( "tcp://127.0.0.1:9293" );
string request = "Hello";
requester.Send( request, Encoding.Unicode );
byte[] reply = null;
try {
reply = requester.Recv();
}
catch( ZMQ.Exception e) {
Console.WriteLine( "Exception: {0}", e.Message );
}
Weather weather = packer.Unpack<Weather>( reply );
Console.WriteLine( "The temp of zip {0} is {1}", weather.zipcode, weather.temperature );
System.Threading.Thread.Sleep( 5000 );
}
}
}
解决方法:
用任何语言编写的大多数程序都可以通过套接字进行通信.因此,C#套接字侦听器可以侦听C发送器.它们通过交换字节序列来完成(非常简化)
您在这里所做的是使用MsgPack在字节数组中序列化C#对象并将其发送过来.另一方面,使用同一MsgPack对C#对象进行反序列化.
除非您的序列化/反序列化库支持,否则这在编程语言中将不起作用,在您的情况下MsgPack不支持.
参加这个C#课程
public class Weather
{
public int zipcode;
public int temperature;
public int humidity;
}
等效的C类
class Weather
{
public:
int zipcode;
int temperature;
int humidity;
}
根据您的操作系统,C语言中的sizeof(int)将为4个字节(字符). C#中的sizeof(int)也是4个字节.
因此,从理论上讲,您可以在C和C#程序之间的套接字连接上交换12(4 * 3)个字节,从而使天气对象在两侧几乎相同
标签:zeromq,msgpack,c,c-4 来源: https://codeday.me/bug/20191202/2086006.html