2012-07-03 232 views
1

我正在开发针对xbmc的python服务,并且我无望地陷入困境。 XBMC具有通过JSON-RPC进行通信的TCP API。 XBMC具有服务器TCP套接字,主要用于接收命令和响应,但如果系统中发生任何事情,它会向TCP发送“通知”。问题是我需要创建TCP客户端,它的行为类似于服务器,因此它能够接收到这个“通知”。无论我在哪里运行socket.recv(4096)它都会等待数据并查找我的代码,因为我需要循环我的代码。的代码结构基本上是这样的:Python“推送服务器”tcp客户端

import xbmc, xbmcgui, xbmcaddon 

class XPlayer(xbmc.Player) : 
    def __init__ (self): 
     xbmc.Player.__init__(self) 
    def onPlayBackStarted(self): 
     if xbmc.Player().isPlayingVideo(): 
      doPlayBackStartedStuff() 

player=XPlayer() 
doStartupStuff() 

while (not xbmc.abortRequested): 
    if xbmc.Player().isPlayingVideo(): 
     doPlayingVideoStuff() 
    else: 
     doPlayingEverythingElseStuff() 

    xbmc.sleep(500) 
    # This loop is the most essential part of code 

if (xbmc.abortRequested): 
    closeEverything() 
    xbmc.log('Aborting...') 

我什么都试过线程,多处理,堵,非阻塞和没有任何帮助。 谢谢,

+0

代码中的哪个位置在尝试recv命令? –

+0

你看过使用选择模块吗? (http://docs.python.org/library/select.html)(http://www.doughellmann.com/PyMOTW/select/) –

+0

@PaulSeeb无论你在哪里运行recv,所有落后的东西都不会执行。 – Tomas

回答

1

你可能想选择(),轮询()或epoll的(): http://docs.python.org/library/select.html

这段Python管进步米的应用程序使用选择,作为一个例子: http://stromberg.dnsalias.org/~strombrg/reblock.html

如果你知道什么样的分隔符将协议的各个部分分开,你也可能会发现这是有用的,而不需要选择或类似的: http://stromberg.dnsalias.org/~strombrg/bufsock.html 它很优雅地处理“阅读下一个空字节”,“阅读最多100个字节“等