如何将枚举发送到python-tcp服务器

本文关键字:python-tcp 服务器 枚举 | 更新日期: 2024-10-19 03:18:55

我正试图让两个系统进行通信,我希望我的C#应用程序与用Python编写的TCP服务器进行垃圾通信。

首先我想到了序列化,并很好地了解了谷歌的protobuf。但是,如果您有复杂的类型和数据结构,就不需要序列化吗。我没有。我只想发送一个枚举(枚举元素的默认基础类型是int(带符号的32位整数))。

但是定义的枚举相当大(C#):

[Flags]
public enum RobotCommands
{
    reset = 0x0,        // 0
    turncenter = 0x1,   // 1
    turnright = 0x2,    // 2
    turnleft = 0x4,     // 4
    standstill = 0x8,   // 8
    moveforward = 0x10, // 16
    movebackward = 0x20,// 32
    utility1on = 0x40,  // 64
    utility1off = 0x80, // 128
    utility2on = 0x100, // 256
    utility2off = 0x200 // 512
}

那么,我真的需要序列化吗?Python读取我发送的枚举的最简单方法是什么?

我试着把它作为字符串发送,希望能把它们转换回来,但它们似乎是字符串:

#!/usr/bin/env python
import socket
TCP_IP = '192.168.1.66'
TCP_PORT = 30000
BUFFER_SIZE = 20  # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while True:
    data = conn.recv(BUFFER_SIZE).encode("hex")
    print "received data:", data    
    if( (data & 0x8) == 0x8 ):
        print("STANDSTILL");
    if not data: break
    conn.send(data)
conn.close()

如何将枚举发送到python-tcp服务器

只需将enum作为字符串传递即可。您可以使用int方法将其返回到integer。

cmd = int(data);

如果您想要十六进制版本,请使用:

cmd = hex(int(data))

int(x[, base]) -> integer                                                                           
Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string.  If base is zero, the proper base is guessed based on the
string content.  If the argument is outside the integer range a
long object will be returned instead.

hex(number) -> string                                                                               
Return the hexadecimal representation of an integer or long integer.

在这种情况下,我只会发送底层值的4字节网络字节顺序块,即

RobotCommands cmd = ...
int i = (int) cmd;

您可以通过多种方式获取字节数;也许是NetworkStream上的BinaryWriter,也许是BitConverter,或者只是移位运算符。然后用其他语言读取相同的4个字节,并将它们视为一个整数。您应该能够用任何语言将整数强制转换为ipenum,或者:只使用位运算符。