A
A
Andrey Prokopyuk2013-05-15 10:01:33
Python
Andrey Prokopyuk, 2013-05-15 10:01:33

Twisted: socket server under high load

The task is to make a server that forwards strings between certain clients. In principle, the task is not too difficult, and the principle from the chat example from the documentation is almost suitable for its implementation:

The code
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):

    def __init__(self, users):
        self.users = users
        self.name = None
        self.state = "GETNAME"

    def connectionMade(self):
        self.sendLine("What's your name?")

    def connectionLost(self, reason):
        if self.users.has_key(self.name):
            del self.users[self.name]

    def lineReceived(self, line):
        if self.state == "GETNAME":
            self.handle_GETNAME(line)
        else:
            self.handle_CHAT(line)

    def handle_GETNAME(self, name):
        if self.users.has_key(name):
            self.sendLine("Name taken, please choose another.")
            return
        self.sendLine("Welcome, %s!" % (name,))
        self.name = name
        self.users[name] = self
        self.state = "CHAT"

    def handle_CHAT(self, message):
        message = "<%s> %s" % (self.name, message)
        for name, protocol in self.users.iteritems():
            if protocol != self:
                protocol.sendLine(message)


class ChatFactory(Factory):

    def __init__(self):
        self.users = {} # maps user names to Chat instances

    def buildProtocol(self, addr):
        return Chat(self.users)


reactor.listenTCP(8123, ChatFactory())
reactor.run()


But I did not find enough information about how such a program will behave if the load is large, several hundred or even thousands of simultaneous connections. I would like to learn more information from comrades experienced in this field.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arkady, 2013-05-17
@Andre_487

It will lead well if you use a more productive pool (epoll, poll) - then everything will be fine :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question