从外部套接字线程关闭套接字

时间:2016-05-08 19:36:36

标签: python python-2.7 sockets

我正在使用Mac的自动化程序Indigo。在我正在工作的插件中,当插件通过调用openSocket(self)开始时打开套接字。套接字打开后,Indigo方法runConcurrentThread(self)在一个单独的线程中运行,以接收来自客户端的任何数据。

我的问题是当调用插件关闭或重新加载时,由runConcurrentThread(self)创建的线程应该停止但它会超时并强制关闭。必须首先关闭插座,这样才能阻止线程关闭,但我无法确定如何操作。

非常感谢任何建议。

# http://wiki.indigodomo.com/doku.php?id=indigo_6_documentation:plugin_guide
# called by startup(self) on starting the plugin
def openSocket(self):

    self.debugLog('openSocket method called')

    for dev in indigo.devices.iter("self"):
        props = dev.pluginProps

    self.PORT = int(dev.pluginProps['rpiSockPort'])  # Arbitrary non-privileged port 8888 is a good one

    if dev.pluginProps['rpiHost'] == "all":
        HOST = ''
    else:
        HOST = dev.pluginProps['rpiHost'] 

    self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    self.debugLog('Socket created')

    try:
        self.s.bind((HOST, self.PORT))
    except socket.error , msg:
        self.debugLog('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
        sys.exit()

    self.debugLog('Socket bind complete')

    self.s.listen(5)

    self.debugLog('Socket now listening')       


#called by Indigo after startup(self)
def runConcurrentThread(self):

    try:

        while True:
            self.errorLog("runConcurrentThread starting")

            #wait to accept a connection - blocking call
            conn, addr = self.s.accept()
            connIp = addr[0]
            connPort = str(addr[1])

            data = conn.recv(1024)

            reply = 'the server received ' + data + '\n'

            if not data: 
                sys.exit()

            conn.sendall(reply)

            # method to update the data in Indigo
            self.updateDeviceStates(self.PORT, connIp, connPort, data)


    except self.StopThread:
        self.debugLog("rpi main thread stopping")

0 个答案:

没有答案
相关问题