Python socket: trying to receive a new TCP message within a while loop

依然范特西╮ 提交于 2021-02-11 14:24:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!