【问题标题】:Python - Sending hex array via UDPPython - 通过 UDP 发送十六进制数组
【发布时间】:2016-04-11 22:07:52
【问题描述】:

是的,我知道 UDP 不好,但不幸的是我别无选择 - 我的服务器只接受 UDP...

我有一个包含十六进制值的列表,需要将其发送出去 UDP。

如果我尝试发送我得到的列表 - 'TypeError: 必须是字符串或缓冲区,而不是列表'

如果我转换为字符串(在我的代码中称为 aList),我会得到 - 'TypeError:需要一个整数' aList 的打印 = 09004000e3f00005f5

如果我将 aList 转换为基数为 16 的 int,我会得到 - 'TypeError: 必须是字符串或缓冲区,不能长'

怀疑这是基本的东西,但我错过了。

简单代码如下::

import socket   #for sockets    

UDP_PORT    = 21105;
UDP_HOST    = '10.194.34.151';


z21 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def _getLocoInfo (id):
    arr        = [ 0x09, 0x00, 0x40, 0x00, 0xE3, 0xF0, 0x00, id]
    arr.append(arr[5]^arr[6]^arr[7])
    return arr

msg = _getLocoInfo(0x05)
aList = "".join("%02x" % b for b in msg)

print (a)

try :
    z21.send(msg ,(UDP_HOST, UDP_PORT) )
     # receive data from client (data, addr)
    d = s.recvfrom(1024)

    print ('Server reply : ' + reply)

except socket.error as e:
        print ('Error Code : ' + str(e[0]) + ' Message ' + e[1])
        sys.exit()

【问题讨论】:

  • 你使用的是 Python 2 还是 Python 3?

标签: python sockets udp hex


【解决方案1】:

我对 python 的 socket 模块不是很了解,但是看着 this 页面我觉得你缺少两件事:

  • 尝试使用 z21.sendto 代替 z21.send
  • 尝试使用 bytes() 将您的消息转换为字节缓冲区

所以结果应该是这样的:

... other code

try:
  z21.sendto(bytes(msg) ,(UDP_HOST, UDP_PORT))

... following code

我希望这会有所帮助。

【讨论】:

  • 那你看一下。我不觉得自己像个笨蛋吗。看起来它现在发送但没有回复,所以是时候启动wireshark了。但现阶段看起来不错。
猜你喜欢
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
相关资源
最近更新 更多