由于socket recv回调,线程没有干净地结束

dgjrabp2  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(173)

当执行shutdown处理程序回调时,我试图关闭套接字并终止线程(我通过ctrl+c发送sigint信号)
主要的

from example import Example

if __name__ == '__main__':

    exmpl = Example()
    success = exmpl.connect('', 2000)

    if success:
        rospy.on_shutdown(exmpl.shutdown_handler)

        rospy.spin()

导入类

import socket
import threading

class Example(object):

    def connect(self, host='', port=2000):
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(10)
            self.sock.bind((host, port))
            self.sock.listen(1)
            self.conn, self.addr = self.sock.accept()
            self.sock.settimeout(None)

            self.t = threading.Thread(target=self.recv_msg)
            self.t.start()

            return True

        except Exception as e:
            return False

        except Exception as timeout:
            return False

    def recv_msg(self):
        while True:
            recv_msg = self.conn.recv(1024)
            print(recv_msg)

    def shutdown_handler(self):
        try:
            self.sock.close()
            self.t.join()
        except Exception as e:
            print(e)

在这个应用程序中,recv\u msg总是在执行,因为数据总是不断出现。所以,当我发送sigint时,shutdown处理程序启动并只执行语句sock.close(),而不是t.join(),线程永远不会结束

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题