Search code examples
pythonsocketstcpudp

Running separate code while a socket server is running?


How can I have a socket server running that accepts incoming connections and deals with that part of the code, while not having code waiting for new connections stuck in that same loop?

I am just starting trying to learn. Would a TCP Handler be useful?

I just need some simple examples on this topic. I'm wanting something like having a commands portion in the server. So i can do certain things while the server is running.

EDIT: What I'm trying to do:

1 - TCP server for multiple clients
2 - Respond to more than one at a time when needed
3 - Text input availability at all time, to be used for getting/setting info
4 - A simple way to get/save client address info. Currently using a list to save them. 

Solution

  • Python has builtin support of asynchronous socket handling in asyncore module (http://docs.python.org/library/asyncore.html).

    Asynchronous socket handling means that You have to execute at least one iteration of socket processing loop inside Your code (main loop):

    asyncore.loop(count=1)
    

    Example taken from documentation:

    import asyncore
    import socket
    
    class EchoHandler(asyncore.dispatcher_with_send):
    
        def handle_read(self):
            data = self.recv(8192)
            if data:
                self.send(data)
    
    class EchoServer(asyncore.dispatcher):
    
        def __init__(self, host, port):
            asyncore.dispatcher.__init__(self)
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            self.set_reuse_addr()
            self.bind((host, port))
            self.listen(5)
    
        def handle_accept(self):
            pair = self.accept()
            if pair is None:
                pass
            else:
                sock, addr = pair
                print('Incoming connection from %s' % repr(addr))
                handler = EchoHandler(sock)
    
    server = EchoServer('localhost', 8080)
    # Note that here loop is infinite (count is not given)
    asyncore.loop()
    

    Each time the socket accepts the connection handle_accept is called by the loop. Each time the data is available to read from socket handle_read is called and so on.

    You can use both TCP and UDP sockets in this manner.