asyncore套接字未正确关闭

时间:2012-08-09 20:35:36

标签: python sockets asyncore

我写过(大部分是复制的)一个非常简单的python脚本,用作xbmc的来电显示插件。除了关闭套接字外,它按预期工作。我已经确认xbmc.abortRequested(XBMC正在关闭的通知)确实设置为True,因此循环应该结束。但它没有(似乎挂起)并且xbmc在清理过程中大约5秒后杀死了脚本。这个不合适的退出不会导致任何问题,但我更喜欢脚本正确退出。我无法弄清楚我是否可以设置某种其他超时或什么。谢谢你的帮助。

道格

我的代码:

import socket, threading, thread, sys, asyncore, xbmc, xbmcgui, xbmcaddon
from time import *
from string import *

xbmc.log("YAC Listener: Starting")
PORT = 10629

class Server(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind((host, port))
        self.listen(1)

    def handle_accept(self):
        socket, address = self.accept()
        ConnectionHandler(socket)

    def handle_close(self):
        self.close()
        xbmc.log("YAC Listener: Closing Port")

class ConnectionHandler(asyncore.dispatcher_with_send):
    def handle_read(self):
        self.buffer = self.recv(1024)
        self.buffer = split(self.buffer[5:], "~")
        self.close()
        global data
        if len(self.buffer) > 1:
            name = self.buffer[0]
            number = self.buffer[1]
                xbmc.executebuiltin("XBMC.Notification("+name+","+number+",7000,special://home/addons/script.yaclistener/phone.png)")
        else:
            data = self.buffer

s = Server('', PORT)

while not xbmc.abortRequested:
    asyncore.loop(timeout=1)

s.close()
sys.exit()
xbmc.log("YAC Listener: Exiting")

1 个答案:

答案 0 :(得分:1)

“timeout”具有略微不同的含义(大致可以视为循环粒度)。

所以结束文件代码应该像下面的smth一样:

...
while not xbmc.abortRequested:
    asyncore.loop(timeout=1, count=1)

# this will try to close ALL current connections:
asyncore.close_all()
# this will give some time (up to 5 seconds) for things to settle down:
asyncore.loop(timeout=1, count=5)
sys.exit()
xbmc.log("YAC Listener: Exiting")