Created
June 4, 2013 08:38
-
-
Save madssj/5704525 to your computer and use it in GitHub Desktop.
A simple python echo server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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