我为两台PC创建了插槽,一台是Raspberry Pi,另一台是我的笔记本电脑。我只连接了两个,然后发送字符串来测试连接。如果我从RPi发送字符“ q”,则我的PC应该跳出循环并关闭连接,但不会。 print("Listening")
部分仍在运行。为什么?参见下面的代码。
import socket
import time
# IP address of this PC.
TCP_IP = '192.168.137.1'
# Port.
TCP_PORT = 5005
# Size of buffer.
BUFFER_SIZE = 1024
# Create a socket, connect and listen to it.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print('Connection address:', addr)
while 1:
print("Listening")
data = conn.recv(BUFFER_SIZE)
data = data.decode()
if data=='q':
break
if data:
print ("Received data:", data)
# Echo back.
conn.send(data.encode())
time.sleep(1)
print("It breaks.")
conn.close()
s.close()
答案 0 :(得分:0)
TCP is a stream oriented protocol. So data transmitted is a stream not a sequence of messages. So when you expect data
to be q
it actually is some_data_sent_before_q_and_finally_q
.
The simplest way to repair the code is to use if data.endswith('q')
instead of if data=='q'
. May work and may not depending on how you actually use the connection. For example, this approach may fail with some_data_sent_before_q
pretty long pause more_data_and_q
and with some_data_sent_before_q_and_finally_q_plus_something_else_why_not
.
Little bit more advanced way to solve the problem is to divide the stream into messages with separators - message_1<separator>message_2<separator>q<separator>
. This method will allow you to treat every message separately.