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

标签 c# python sockets serialization tcp

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

首先想到的是序列化,然后好好看了下google的protobuf。但是,如果您有复杂的类型和数据结构,您是否只需要序列化。我不。我只想发一个enum (枚举元素的默认基础类型是 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()

最佳答案

只需将枚举作为字符串传递即可。您可以使用 int 方法将它们恢复为整数。

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.

关于c# - 如何将枚举发送到 python tcp 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11816035/

相关文章:

c# - 从 Compact .Net 1.0 应用程序启动另一个应用程序

c# - 如何从 .exe 文件获取连接字符串。有没有可能?

c# - 编辑模式下 DataGridView C# 行中的默认值

Python:将多个 .txt 文件解析为单个 .csv 文件?

c - 如何在单个服务器中结合 TCP 和 UDP?

javascript - 为什么记录记录器/webBot 在刷新网页后会存储之前对话的事件?

python - glob 多个 CSV 和 np.arange

python - 在 Python 中计算加权成对距离矩阵

c# - 为什么我不能使用 TCP 客户端发送两个消息? (续)

python - python 网络服务器上打开的套接字数量不断增加