我有一个程序处理网络中的一些设备。该程序为每个设备创建一个进程,每个进程在循环中运行 socket.recv 函数以接收来自连接设备的消息。当我关闭设备然后再打开时,程序和设备之间的连接将丢失,但 recv 函数不会返回任何内容或引发任何异常,并且进程保持阻塞。如何处理这个问题这是我的代码:
if __name__ == '__main__':
ip = sys.argv[1]
port = sys.argv[2]
pingInterval = float(sys.argv[3])
deviceId = sys.argv[4]
print("A card reader started for ", ip)
Thread(target=setThePingerThread, args=(pingInterval,)).start()
while True:
clientsock = socket (AF_INET, SOCK_STREAM)
connectionSuccessful = False
while not connectionSuccessful:
try:
clientsock.connect((ip, int(port)))
connectionSuccessful = True
print('socket connected to ', ip, port)
except Exception as e:
print('Can''t connect to the device! device ip =>', ip)
time.sleep(5000)
pass
try:
mybuffer = bytes()
data = bytes()
cardNumbers = []
while True:
mybuffer = clientsock.recv(100)
data = data + mybuffer
cardNumbers, data = retreiveCardNumbers(data)
#print('debug: cardNumbers=', cardNumbers, ' data=',data, ' data-decoded=',data.decode("ascii"))
for cardNumber in cardNumbers:
print('A card hit:', cardNumber)
sendToQueue(cardNumber, deviceId)
except Exception as e:
print('Error processing card number! device ip =>', ip, e)