[Python] Message passing between Python and C#

Messaging in Python and C#

Recently, when I was working on some small projects with my friends, I made a combination of Python as the server and C# as the client. Everyone showed their talents, and there are many ways to go  ̄| ̄|

Use Json as intermediate file

Communication between two different languages ​​requires a unified data exchange format, and Json is undoubtedly our first choice.
Due to the authenticity of the dishes, they are all confused about how to convert the other party's language. Here is a Json conversion comparison table:

Python Json C#
dict object class
list, tuple array list
str, unicode string string
int, long, float number int,long,float
True true true
False false false
None null null

This only corresponds to the unified message format on both sides, and Json can be easily implemented as an intermediate file.

For C#, we need to introduce Newtonsoft.Json (or other packages that can perform Json operations, which can be downloaded from the Json official website). Taking Newtonsoft.Json as an example, we mainly use:

function meaning
JsonConvert.SerializeObject(object value) Serialize the class into a Json string
JsonConvert.DeserializeObject<T>(string value) Deserialize the Json string into a specified class

For Python, using the JSON function requires importing the json library: import json.

function meaning
json.dumps Encode a Python object into a JSON string
json.loads Decode an encoded JSON string into a Python object

Big endian vs little endian issues

Originally, this problem would not have occurred. Due to the use of Socket, when dealing with subpackage and sticky packets, some wonderful operations forced me to record this problem, and then post the key parts:

C# client:
insert image description here

Python server:
insert image description here
Here we use the simplest way to deal with subpackages and sticky packets, that is, length + message content. The result is always wrong when running. The server does not seem to receive anything. After repeated debugging, it is found that there is a problem with the parsing of the length:

The data sent by the C# BitConverter.GetBytes method is:
11 0 0 0 (size: 11)

The data in the Python head is:
b'\x0b\x00\x00\x00' (size: 184549376)

It is obvious that C# is processing data in little endian, while Python is processing in big endian, all of this stems from the confident exclamation point! ᕙ༼ ͝°依° ༽ᕗ

From the official documentation
Change to = world peace ( ̄▽ ̄)~*


The strength is low, please bear with me (*・ω-q)

Guess you like

Origin blog.csdn.net/zigzagbomb/article/details/101212111