开发者

Interacting servers using Twisted?

开发者 https://www.devze.com 2023-02-14 07:19 出处:网络
I have been dabling in some Twisted and I\'ve come across a problem.I\'开发者_StackOverflow中文版m implementing a couple servers that can be connected to using telnet localhost x

I have been dabling in some Twisted and I've come across a problem. I'开发者_StackOverflow中文版m implementing a couple servers that can be connected to using telnet localhost x

My code handles it like this:

reactor.listenTCP(12001, server1, ....)

reactor.listenTCP(12002, server2, ....) etc.

These then use my factory to build a protocol

I'm wondering how I can get these servers to interact with each other. For example, let's say a client sends a request to update a value common across each server and I want to relay this value to the other servers to update their current value. I looked into reactor.connectTCP but this doesn't seem to do what I want. Is there a way to connect to my servers without using the telnet command?


Sure. Use normal Python techniques for this. Let's take your example of a value being updated. I'll make it a simple counter that might be incremented by connections to one server and the value sent out to connections to the other server:

from twisted.internet import reactor
from twisted.internet.protocol import ServerFactory, Protocol

class Counter(object):
    def __init__(self):
        self._value = 0

    def increment(self):
        self._value += 1

    def get(self):
        return self._value


class Incrementor(Protocol):
    def connectionMade(self):
        self.factory.value.increment()
        self.transport.loseConnection()


class Reporter(Protocol):
    def connectionMade(self):
        self.transport.write("Value is %d\n" % (self.factory.value.get(),))
        self.transport.loseConnection()

server1 = ServerFactory()
server1.protocol = Incrementor

server2 = ServerFactory()
server2.protocol = Reporter

server1.value = server2.value = Value()

reactor.listenTCP(12001, server1)
reactor.listenTCP(12002, server2)
reactor.run()

The two factories are now sharing a piece of mutable state. The protocols can access their factories because the default ServerFactory helpfully sets itself as an attribute on protocols it instantiates, so the protocols can also reach the shared mutable state on the factories. One increments the counter, the other retrieves the value.

You can construct many scenarios like this with shared state and method calls onto non-protocol, non-factory objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消