import asynchat import asyncore CLIENT = u'Oboe/0.1' DEBUG = True class Haver(asynchat.async_chat): def __init__(self, conn, username): asynchat.async_chat.__init__(self, conn) self.buffer = [] self.username = username self.set_terminator(u'\x0D\x0A') self.put(u'HAVER', CLIENT) def run(self): asyncore.loop() def step(self): asyncore.loop(count=1) def put(self, *args): text = [] for element in args: new = element new = new.replace(u'\x1b', u'\x1be') new = new.replace(u'\x0D', u'\x1br') new = new.replace(u'\x0A', u'\x1bn') new = new.replace(u'\x09', u'\x1bt') text.append(new) cmd = u'\x09'.join(text) + u'\x0D\x0A' if DEBUG: print u'->', repr(cmd) self.push(cmd) def bye(self, reason=None): if reason: self.put(u'BYE', reason) else: self.put(u'BYE') self.close() def collect_incoming_data(self, data): self.buffer.append(data) def found_terminator(self): data = u''.join(self.buffer).split(u'\x09') self.buffer = [] command = data[0] raw_args = data[1:] args = [] for element in raw_args: new = element new = new.replace(u'\x1br', u'\x0D') new = new.replace(u'\x1bn', u'\x0A') new = new.replace(u'\x1bt', u'\x09') new = new.replace(u'\x1be', u'\x1b') args.append(new) if DEBUG: print u'<-', command, args if hasattr(self, 'OnMessage'): self.OnMessage(command, *args) cb = u'On%s' % command if hasattr(self, cb): getattr(self, cb)(*args) def OnPING(self, token): self.put(u'PONG', token)