gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:52:44 26 4
gpt4 key购买 nike

我正在尝试让两个系统进行通信,我希望我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com