Python Server Socket Without Infinite Loop?
Question: I'd like to create a class that allows sending and receiving on the same port
and create an event-driven application from incoming messages while the
program does it operations. I don't have much experience with sockets so I
don't know how to do this. Here is my SimpleSock class that so far just binds
the socket. I also put an infinite loop in there to listen for connections but
know this won't work for what I want because the program won't be able to do
anything besides listen.

    
    
    import socket
    
    class SimpleSock:
    
        def __init__(self, ip=None, port=None):
            if ip == None or port == None:
                print("SimpleSock cannot init without an ip and port")
            else:
                self.ip = ip
                self.port = port
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
                print("attempting connection to " + self.ip + " on port " + str(self.port))
    
                self.socket.bind((self.ip, self.port))
                self.socket.listen(5)
    
                print("connected")
    
                while True:
                    (clientsocket, address) = self.socket.accept()
                    #do something
    

How can I write a listen without and infinite loop? Do I need to use threads?


Answer: Event-driven network applications in Python can be built using frameworks like
Python Twisted or Tornado. You can see a comparison in another question here:
[When to use Tornado, when to use Twisted / Cyclone / GEvent /
other](http://stackoverflow.com/questions/13941903/when-to-use-tornado-when-
to-use-twisted-cyclone-gevent-other)

The general idea is that the framework will let you register callbacks for
when events happen like data waiting on a socket, and the framework will
usually be your "main loop" (so it takes over control of the main thread
typically). You do not need threads most of the time--everything can be
multiplexed in a single thread so long as all your event sources are waitable
using select() or similar.

