【问题标题】:Python "push server" tcp clientPython“推送服务器”tcp客户端
【发布时间】:2012-07-03 20:36:42
【问题描述】:

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

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...')

我尝试了所有线程、多处理、阻塞、非阻塞,但没有任何帮助。 谢谢,

【问题讨论】:

标签: python tcp json-rpc


【解决方案1】:

您可能需要 select()、poll() 或 epoll(): http://docs.python.org/library/select.html

这个 Python pipe-progress-meter 应用程序使用 select,例如: http://stromberg.dnsalias.org/~strombrg/reblock.html

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2014-03-08
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多