Skip to content

Instantly share code, notes, and snippets.

@madssj
Created June 4, 2013 08:38
Show Gist options
  • Save madssj/5704525 to your computer and use it in GitHub Desktop.
Save madssj/5704525 to your computer and use it in GitHub Desktop.
A simple python echo server.
import asyncore
import asynchat
import socket
class Lobby(object):
def __init__(self):
self.clients = set()
def leave(self, client):
self.clients.remove(client)
def join(self, client):
self.clients.add(client)
def send_to_all(self, data):
for client in self.clients:
client.push(data)
class Client(asynchat.async_chat):
def __init__(self, conn, lobby):
asynchat.async_chat.__init__(self, sock=conn)
self.in_buffer = ""
self.set_terminator("n")
self.lobby = lobby
self.lobby.join(self)
def collect_incoming_data(self, data):
self.in_buffer += data
def found_terminator(self):
if self.in_buffer.rstrip() == "QUIT":
self.lobby.leave(self)
self.close_when_done()
else:
self.lobby.send_to_all(self.in_buffer + self.terminator)
self.in_buffer = ""
class Server(asynchat.async_chat):
def __init__(self):
asynchat.async_chat.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(("127.0.0.1", 12345))
self.listen(5)
self.lobby = None
def set_lobby(self, lobby):
self.lobby = lobby
def handle_accept(self):
sock, addr = self.accept()
client = Client(sock, self.lobby)
if __name__ == '__main__':
lobby = Lobby()
server = Server()
server.set_lobby(lobby)
asyncore.loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment