a simple tcp server sample

Jean-Paul Calderone exarkun at divmod.com
Wed Nov 7 20:59:43 CET 2007

On Wed, 07 Nov 2007 18:54:39 -0000, Tzury Bar Yochay <afro.systems at gmail.com> wrote:
>hi, the following sample (from docs.python.org) is a server that can
>actually serve only single client at a time.
>In my case I need a simple server that can serve more than one client.
>I couldn't find an example on how to do that and be glad to get a
>Thanks in advance
>import socket
>HOST = ''      # Symbolic name meaning the local host
>PORT = 50007            # Arbitrary non-privileged port
>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>s.bind((HOST, PORT))
>conn, addr = s.accept()
>print 'Connected by', addr
>while 1:
>        data = conn.recv(1024)
>        if not data:
>                break
>        conn.send(data)

Even simpler, use Twisted:

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

    HOST = ''      # Symbolic name meaning the local host
    PORT = 50007            # Arbitrary non-privileged port

    class Echo(Protocol):
        def connectionMade(self):
            print 'Connection from', self.transport.getPeer()

        def dataReceived(self, bytes):

    factory = ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(HOST, PORT, factory)

This doesn't have the bug your version has (where it randomly drops some
data on the floor) and handles multiple clients.

Check it out:  http://twistedmatrix.com/


More information about the Python-list mailing list