问题
Hope everyone's doing well.
I have a problem I've been trying to solve for a good while now with no success... I have this function that listens for commands sent by pressing various buttons on a website. Once it receives a command it sends it further down the serial port:
def write(self):
while self.alive:
try:
data = self.socket.recv(1024)
print('Data received through TCP: ' + str(data))
recvdStr = data.decode('UTF-8')
if not data:
break
self.serial.write(recvdString.encode('utf-8'))
print('Data sent through serial: ' +str(recvdStr))
self.alive = False
self.thread_read.join()
The above works as intended...
I'm now trying to expand this function so that when it receives a specific command from that website it executes a specific part of the function (while still listening to the socket) until it receives another command telling that part of the function to stop and return to just listening and forwarding (as shown in the code above).
The way I tried to implement it can be seen here:
def write(self):
while self.alive:
try:
data = self.socket.recv(1024)
print('Data received through TCP: ' + str(data))
recvdStr = data.decode('UTF-8')
if data == b'start':
self.serial.write(data.encode('utf-8'))
while True:
newData = self.socket.recv(1024)
newMessage = 'works'
self.serial.write(newMessage.encode('utf-8'))
time.sleep(0.5)
if newData == b'stop':
break
if not data:
break
self.serial.write(recvdString.encode('utf-8'))
print('Data sent through serial: ' +str(recvdStr))
self.alive = False
self.thread_read.join()
The sort of behaviour I get from the above is that when it receives the 'start' message it repeatedly sends the 'newMessage' down the serial port (as intended), but when I click a button on my website that sends the 'stop' message, the function doesn't receive it and the 'newMessage' is still being sent.
I'd like to stop that loop once the 'stop' message has been received and return to normal operation...
Any help would be greatly appreciated.
Thank you,
Rob
来源:https://stackoverflow.com/questions/60368268/python-socket-trying-to-receive-a-new-tcp-message-within-a-while-loop