The code for a very simple asynchronous socket server written in python utilizing the asynchat module. It’s all in good fun.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 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() |
Booting the server is a matter of python echoserver.py.
After that, telnet can be used to induce messages, as such:
$ telnet localhost 12345 foo fooThe same will be true for any amount of clients. This is so simple. Love it.
Wow thanks for the great bit of code. I’m a newbie at Python and this is exactly what I was looking for to learn asyncore
error in line 22: asynchat.async_chat.init(self, sock=conn)
True.
connshould besock.