a simple tcp server sample

Jean-Paul Calderone exarkun at divmod.com
Wed Nov 7 14:59:43 EST 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
>hint.
>
>Thanks in advance
>
>import socket
>
>HOST = '127.0.0.1'      # 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))
>s.listen(1)
>conn, addr = s.accept()
>
>print 'Connected by', addr
>
>while 1:
>        data = conn.recv(1024)
>        if not data:
>                break
>        conn.send(data)
>
>conn.close()

Even simpler, use Twisted:

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

    HOST = '127.0.0.1'      # 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):
            self.transport.write(bytes)

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

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/

Jean-Paul



More information about the Python-list mailing list