我有一个程序,它接受UDP上的坐标,移动一些设备,然后在工作完成后回复。
我好像和这家伙有同样的问题:
我的密码在这里:
import socket
import struct
import traceback
def main():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('',15000))
reply_sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
try:
data,addr = sock.recvfrom(1024)
if data is not None:
try:
coords = struct.unpack('>dd',data)
#Stuff happens here
print(f'moved probe to {coords}')
reply_sock.sendto(bytearray.fromhex('B'),('10.0.0.32',15001))
except:
traceback.print_exc()
try:
reply_sock.sendto(bytearray.fromhex('D'),('10.0.0.32',15001))
except:
traceback.print_exc()
break
except:
pass程序的行为就像sendto调用刚刚被传递一样;它接受数据包,执行print语句,然后循环(它可以多次执行循环,但从不应答)。我在看wireshark,没有任何数据包被发送出去。没有任何错误被抛出。
知道为什么会这样吗?
发布于 2018-10-24 16:33:39
来自文献资料
字符串必须包含每个字节两个十六进制数字,忽略ASCII空格。
所以发生了这样的事情:
$ python3
Python 3.6.6 (default, Sep 12 2018, 18:26:19)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> bytearray.fromhex('B')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: non-hexadecimal number found in fromhex() arg at position 1
>>> 试试这个:
reply_sock.sendto(bytearray.fromhex('0B'),('10.0.0.32',15001))如果你是这个意思的话。
请注意,您的except正在捕获所有异常,而不仅仅是您所期望的异常,因此您没有看到所导致的错误。考虑在这里使用类似于except OSError的东西。
另外,考虑减少try部分中的代码数量:
coords = struct.unpack('>dd',data)
#Stuff happens here
print(f'moved probe to {coords}')
bytes_to_send = bytearray.fromhex('0B')
try:
reply_sock.sendto(bytes_to_send,('10.0.0.32',15001))
except IOError as e1:
print(e1)
traceback.print_exc()
bytes_to_send = bytearray.fromhex('0D')
try:
reply_sock.sendto(bytes_to_send,('10.0.0.32',15001))
except IOError as e2:
print(e2)
traceback.print_exc()
break这样你就只能保护你想要的代码了。
https://stackoverflow.com/questions/52973794
复制相似问题