![](/img/trans.png)
[英]How I can to create python(or swift) TCP client for my TCP c# server?
[英]How can I send an enum to a python tcp server?
我正在嘗試使兩個系統進行通信,我希望我的C#應用程序與用Python編寫的TCP服務器對話。
首先,我想到了序列化,並且很好地了解了Google的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()
只需將枚舉作為字符串傳遞就可以了。 您可以使用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.
在這種情況下,我只發送基礎值的4字節網絡字節順序塊,即
RobotCommands cmd = ...
int i = (int) cmd;
您可以通過多種方式獲得字節。 也許是NetworkStream上的BinaryWriter,也許是BitConverter,或者只是移位運算符。 然后使用其他語言讀取相同的4個字節,並將它們視為整數。 您應該能夠以任何語言將整數轉換為ipenum,或者:僅使用按位運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.