Created
November 25, 2010 05:53
-
-
Save amcgregor/714970 to your computer and use it in GitHub Desktop.
Asynchronous chat 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
# encoding: utf-8 | |
import logging | |
from functools import partial | |
from marrow.server.base import Server | |
from marrow.server.protocol import Protocol | |
log = logging.getLogger(__name__) | |
class MUSHProtocol(Protocol): | |
def __init__(self, *args, **kw): | |
self.clients = dict() | |
super(MUSHProtocol, self).__init__(*args, **kw) | |
def accept(self, client): | |
log.info("Accepted connection from %r.", client.address) | |
client.write(b"Please enter your user name / handle:\r\n") | |
client.read_until(b"\r\n", partial(self.set_handle, client)) | |
def set_handle(self, client, data): | |
name = data.strip() | |
for user in self.clients: | |
user.write(name + " has entered the room.\r\n") | |
self.clients[client] = name | |
client.write(b"Hello, " + name + "! Type something and press enter. Type /quit to quit.\r\n") | |
if self.clients: | |
client.write(b"The following users are already here: " + b', '.join(self.clients.values()) + b'\r\n') | |
else: | |
client.write(b"There are no other users on the server.\r\n") | |
client.read_until(b"\r\n", partial(self.on_line, client)) | |
def on_line(self, client, data): | |
data = data.strip() | |
if data == b"/quit": | |
name = self.clients[client] | |
del self.clients[client] | |
for user in self.clients: | |
user.write(name + b" has left the room.\r\n") | |
client.write(b"Goodbye!\r\n", client.close) | |
return | |
for user in self.clients: | |
if user is client: continue | |
user.write(self.clients[client] + " says, \"" + data + "\"\r\n") | |
client.write(b"You say, \"" + data + b"\"\r\n") | |
client.read_until(b"\r\n", partial(self.on_line, client)) | |
if __name__ == '__main__': | |
import logging | |
logging.basicConfig(level=logging.INFO) | |
Server(None, 8888, MUSHProtocol).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment