A simple python tcp server

 # a simple tcp server

import SocketServer

class EchoRequestHandler(SocketServer.BaseRequestHandler ):
    def setup(self):
        print self.client_address, 'connected!'
        self.request.send('hi ' + str(self.client_address) + '\n')

    def handle(self):
        data = 'dummy'
        while data:
            data = self.request.recv(1024)
            self.request.send(data)
            if data.strip() == 'bye':
                return

    def finish(self):
        print self.client_address, 'disconnected!'
        self.request.send('bye ' + str(self.client_address) + '\n')

    #server host is a tuple ('host', port)
server = SocketServer.ThreadingTCPServer(('', 50008), EchoRequestHandler)
server.serve_forever()
Advertisements

15 Comments on “A simple python tcp server”

  1. Binny V A says:

    Please put the code in a pre tag – without that the indentation is lost. This would not be a problem for most languages – but for python its an issue.

  2. That’s correct. See this WordPress’ editor modify the text when switching between ‘html’ and ‘design’ modes.

  3. James says:

    I want to hate you now :\
    As hard as I try all my python-network code ever returns is errors -_-
    Die python die.

  4. @James
    I would love to give a hand and help you if you can share more info.
    Long live python

  5. sandrar says:

    Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

  6. […] El otro dia me puse a jugar con un ejemplo de un servidor tcp simple en python que vi aqui […]

  7. Musa says:

    Hi, I need some help about for this subject.

    The data is sent only to clients who submit. But does not send the other connected clients. I want a client sends data to all clients get connected, I think this should be. Waiting for your reply, thanks in advance.

  8. @Musa,
    This Will Do

    from twisted.internet import reactor
    from twisted.internet.protocol import ServerFactory, Protocol
    
    class TCPServerPrtocol(Protocol):        
        def connectionMade(self):
            self.factory.echoers.append(self)
            
        def dataReceived(self, data):
            self.factory.send_all(data)
            
        def connectionLost(self, reason):
            self.factory.echoers.remove(self)
              
    class TCPServerFactory(ServerFactory):
        protocol = TCPServerPrtocol
        echoers = []
    
        def send_all(self, data):
            for client in self.echoers:
                client.transport.write(data)
    
    
    srv = TCPServerFactory()
    reactor.listenTCP(6666, srv)
    reactor.run()
    
  9. Musa says:

    Thanks for the quick reply first. I think this code for to work need Twisted library. I installed it, but this time gave Zope error. EGG have already downloaded a file extension, but I do not know how to set up. Sorry my odd english.

    error: from zope.interface import implements
    ImportError: No module named zope.interface

  10. what platform are you using (windows/linux/mac)?

  11. Musa says:

    windows vista

  12. I guess you should install zope separately then.
    zope.org site is currently down[1] though, but you should be able getting it from other mirrors

    [1] http://img227.imageshack.us/img227/8991/zopeorg.png

  13. Musa says:

    I’ve had previously downloaded. But I do not know what to do and how to set up I could not do anything. I’ve downloaded the file named “zope.interface-3.6.1-py2.6-win32.egg” How to install Windows, this file will?

    http://docs.zope.org/zope2/releases/2.12/INSTALL.html Here is up but I’m not understand anything, I think this is for linux

  14. Musa says:

    Ok. I’m install zope.interface. And I tried the code again, gave a different error:

    return self.protocol.dataReceived(data)
    File “c:\myserver.py”, line 9, in dataReceived
    self.factory.send_all(data)
    File “c:\myserver.py”, line 19, in send_all
    for client in clients:
    exceptions.NameError: global name ‘clients’ is not defined

  15. Musa says:

    Thanks for help! I’m fix it and works perfectly :D


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

    class TCPServerPrtocol(Protocol):
    def connectionMade(self):
    print "A new client connected"
    self.factory.echoers.append(self)

    def dataReceived(self, data):
    print "<<< " + data
    if data == "":
    self.transport.write("")
    else:
    self.factory.send_all(data)

    def connectionLost(self, reason):
    print "A client disconnected"
    self.factory.echoers.remove(self)

    class TCPServerFactory(ServerFactory):
    protocol = TCPServerPrtocol
    echoers = []

    def send_all(self, data):
    for client in self.echoers:
    client.transport.write(data)

    srv = TCPServerFactory()
    reactor.listenTCP(21567, srv)
    reactor.run()


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s