我正在尝试使用套接字(Socket)从Django网站向机器人(Raspberry Pi)发送指令,但是每当我尝试从网站发送第二条指令时,就会出现错误。如果您知道是什么原因导致这种情况,帮助会非常重要! 网站发送视图:
def form_valid(self, form, **kwargs):
robo_pk = self.kwargs['pk']
robo = Robot.objects.get(pk=robo_pk)
PORT = robo.port
SERVER = robo.server
ADDR = (SERVER, PORT)
self.object = form.save()
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
send(form.cleaned_data['path_options'])
send("MESSAGE SENT :) !")
send(DISCONNECT_MESSAGE)
return render(self.request, "dashboard-home/thank-you.html")
错误追踪:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "main.py", line 46, in handle_client
conn.send("MSG Received".encode(FORMAT))
BrokenPipeError: [Errno 32] Broken pipe
相关代码:
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == '!DISCONNECT!':
connected = False
print("disconnect")
break
else:
my_queue.put(msg)
print(f"[{ADDR}] {msg}")
conn.send("MSG Received".encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server Is Listening On {SERVER}")
while True:
print("before")
conn,addr = server.accept()
print("after")
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount()}")
print("[Starting] Server")
threading.Thread(target=start).start()
msg = my_queue.get()