【问题标题】:Python - share sockets between processesPython - 在进程之间共享套接字
【发布时间】:2018-01-16 14:31:32
【问题描述】:

是否可以在 2 个正在运行的进程之间共享套接字对象?

为简化问题,假设我们有两个文件s1.py 和s2.py。两者都是侦听不同端口的 tcp 服务器。

s1.py 正文

from twisted.internet import reactor, protocol

CLIENTS = []

class Echo(protocol.Protocol):
    def connectionMade(self):
        CLIENTS.append(self)

    def dataReceived(self, data):
        self.transport.write(data)

    def connectionLost(self):
        CLIENTS.remove(self)

def main():
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(8000, factory)
    reactor.run()

main()

和 s2.py

from twisted.internet import reactor, protocol

class Echo(protocol.Protocol):

    def dataReceived(self, data):
        for socket in list_of_serialized_redis_CLIENTS_socket_object:
           socket.transport.write(data)

def main():
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(8001, factory)
    reactor.run()

main()

是否可以将 s1.py 中的 CLIENTS 与 s2.py 共享? 也许有一些方法可以序列化CLIENTS并将其存储在redis中。

【问题讨论】:

  • 您希望通过本次分享达到什么目的?您的两个示例程序存在问题,因为它们不执行跨进程同步,因此您尝试发送的任何数据都可能最终与来自另一个的数据交错。这可能与接收方的数据已损坏且无法使用相同。
  • 对于自 Python 3.3 起的 Windows,有 socket.share()

标签: python sockets twisted python-multiprocessing


【解决方案1】:

使用socket.share() 可能不像您想象的那么简单。 首先,它是 Windows 独有的功能,而 Windows 是 Twisted 最少关注的一个平台。 在 Twisted 中访问低级 socket 对象可能会很棘手,因为幕后发生了很多事情,如果更改可能会导致奇怪的结果。 所以换句话说,这条路当然可以走,但不推荐。

如果您愿意接受新的解决方案,我认为 RPC 样式的服务器将解决您的问题。 我的想法是,由于连接对象位于s1 中,因此只需创建一个远程进程即可对这些连接进行“处理”。 其他进程可以连接到该服务器并在s1 的本地对象上执行功能。 Twisted 的Perspective Broker 是您可以利用的现成解决方案。

s1.py

from twisted.internet import reactor, protocol, endpoints
from twisted.spread import pb

class Echo(protocol.Protocol):
    def connectionMade(self):
        self.factory.client_set.add(self)

    def connectionLost(self, reason):
        self.factory.client_set.remove(self)

class Remote(pb.Root):
    def __init__(self, client_set):
        self.client_set = client_set

    def remote_s1_write(self, data):
        msg_tmpl = 'From s1...{0}'
        for client in self.client_set:
            response = msg_tmpl.format(data).encode('utf-8')
            client.transport.write(response)

def main():
    client_set = set()      # container will be shared between the 2 servers

    # setup Echo server
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    factory.client_set = client_set
    echo_server = endpoints.TCP4ServerEndpoint(reactor, interface='localhost', port=8000)
    echo_server.listen(factory)

    # setup PB server
    pb_root = Remote(client_set)
    pb_factory = pb.PBServerFactory(pb_root)
    pb_server = endpoints.TCP4ServerEndpoint(reactor, interface='localhost', port=7999)
    pb_server.listen(pb_factory)

    reactor.run()

main()

s2.py

from twisted.internet import reactor, protocol, endpoints
from twisted.spread import pb

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        remote = self.factory.pb_factory.getRootObject()
        remote.addCallback(lambda obj: obj.callRemote('s1_write', data))
        remote.addCallback(lambda echo: 's1 said: {0}'.format(data))
        remote.addErrback(lambda reason: 'error: {0}'.format(str(reason.value)))
        remote.addCallback(lambda response: print(response))
        self.transport.write(data)

def main():
    # connect to s1's PB server
    pb_factory = pb.PBClientFactory()
    pb_connection = endpoints.TCP4ClientEndpoint(reactor, host='localhost', port=7999)
    pb_connection.connect(pb_factory)

    # setup Echo server
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    factory.pb_factory = pb_factory
    echo_server = endpoints.TCP4ServerEndpoint(reactor, interface='localhost', port=8001)
    echo_server.listen(factory)

    reactor.run()

main()

我冒昧地更新了语法。试试这段代码,看看它是否有效,并询问您是否有任何问题。

【讨论】:

  • PB 非常复杂。它的使用也非常狭窄,因此具有一项不起眼的技术的所有外部缺点。在向任何人推荐之前,我会仔细考虑。
  • 这个想法是使用 PB 来演示设计。在 prod 中,PB 可以(应该?)被另一种 RPC 样式的实现(REST、XML、AMQP、0MQ 等)取代。下次我会记住 PB 的默默无闻。它会很快被弃用或简化吗?对于它的价值,我确实认为这是一个可靠的概念,但它可以从简化的重新设计中受益。
  • 我认为“远程对象引用”协议过于复杂,无法与 Python 进行交互。至少,缺少十年人年的工具开发才能使其变得可行。所以I 会弃用然后删除twisted.spread。不确定 Twisted 项目本身是否会采取这一步(这也许是合理的:现有使用 PB 并且可以工作的软件不应该被破坏。而且该项目在某种程度上缺乏明确声明的方式“这已被放弃,但我们不会故意破坏它”)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 2017-06-14
  • 2014-10-22
  • 2014-01-15
  • 2012-06-17
  • 2016-08-08
  • 1970-01-01
相关资源
最近更新 更多