从Python到C#的套接字消息通过乱码(A socket message from Python to C# comes through garbled)

编程入门 行业动态 更新时间:2024-10-11 17:19:12
从Python到C#的套接字消息通过乱码(A socket message from Python to C# comes through garbled)

我正在尝试使用simplejson和Json.NET在Python服务器和C#客户端之间建立一个非常基本的基于ZeroMQ的套接字链接。 我尝试从Python发送一个dict并将其读入C#中的一个对象。 Python代码:

message = {'MessageType':"None", 'ContentType':"None", 'Content':"OK"} message_blob = simplejson.dumps(message).encode(encoding = "UTF-8") alive_socket.send(message_blob)

消息以普通的UTF-8字符串发送,如果我使用UTF-16,则发送为“'\ xff \ xfe {\ x00”\ x00 ...“等。

C#中的代码是我的问题所在:

string reply = client.Receive(Encoding.UTF8);

UTF-8消息收到“≻潃瑮湥≴> ...”等。

我尝试使用UTF-16并且消息通过OK,但是第一个符号仍然是little-endian \ xFF \ xFE BOM,因此当我尝试将其提供给反序列化器时,

PythonMessage replyMessage = JsonConvert.DeserializeObject<PythonMessage>(reply); //PythonMessage is just a very simple class with properties, //not relevant to the problem

我收到一个错误(显然出现在第一个符号,\ xFF):

Unexpected character encountered while parsing value: .

我正在使用编码的方式显然是错误的。 你能告诉我正确的方法吗?

I'm trying to set up a very basic ZeroMQ-based socket link between Python server and C# client using simplejson and Json.NET. I try to send a dict from Python and read it into an object in C#. Python code:

message = {'MessageType':"None", 'ContentType':"None", 'Content':"OK"} message_blob = simplejson.dumps(message).encode(encoding = "UTF-8") alive_socket.send(message_blob)

The message is sent as normal UTF-8 string or, if I use UTF-16, as "'\xff\xfe{\x00"\x00..." etc.

Code in C# is where my problem is:

string reply = client.Receive(Encoding.UTF8);

The UTF-8 message is received as "≻潃瑮湥≴›..." etc.

I tried to use UTF-16 and the message comes through OK, but the first symbols are still the little-endian \xFF \xFE BOM so when I try to feed it to the deserializer,

PythonMessage replyMessage = JsonConvert.DeserializeObject<PythonMessage>(reply); //PythonMessage is just a very simple class with properties, //not relevant to the problem

I get an error (obviously occurring at the first symbol, \xFF):

Unexpected character encountered while parsing value: .

Something is obviously wrong in the way I'm using encoding. Can you please show me the right way to do this?

最满意答案

UTF-16中必须使用字节顺序标记。 您可以使用UTF-16LE或UTF-16BE来假设特定的字节顺序,并且不会生成BOM。 也就是说,使用:

message_blob = simplejson.dumps(message).encode(encoding = "UTF-16le")

The byte-order-mark is obligatory in UTF-16. You can use UTF-16LE or UTF-16BE to assume a particular byte order and the BOM will not be generated. That is, use:

message_blob = simplejson.dumps(message).encode(encoding = "UTF-16le")

更多推荐

本文发布于:2023-07-18 04:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154799.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乱码   消息   Python   garbled   message

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!