+class Socketlike(abc.ABC):
+ def __init__(self, sock, data):
+ """This default method saves the socket in self.sock and creates self.buffer for getdata(). The data is discarded."""
+ self.sock = sock
+ self.buffer = b''
+
+ def getdata(self):
+ """This default method gets LF or CRLF separated lines from the socket and returns an array of completely-seen lines to the core.
+ This should work well for most line-based protocols (like IRC)."""
+ recvd = self.sock.recv(8192)
+ if recvd == b"": # EOF
+ if len(self.buffer) != 0:
+ # Process what's left in the buffer. We'll get called again after.
+ remaining_buf = self.buffer.decode('utf-8', 'backslashreplace')
+ self.buffer = b""
+ return [remaining_buf]
+ else:
+ # Nothing left in the buffer. Return None to signal the core to close this socket.
+ return None
+ self.buffer += recvd
+ lines = []
+
+ while b"\n" in self.buffer:
+ pieces = self.buffer.split(b"\n", 1)
+ s = pieces[0].decode('utf-8', 'backslashreplace').rstrip("\r")
+ lines.append(pieces[0].decode('utf-8', 'backslashreplace'))
+ self.buffer = pieces[1]
+
+ return lines
+
+ def __str__(self):
+ return '%s#%d' % (self.__class__.__name__, self.sock.fileno())
+ def __repr__(self):
+ return '<%s.%s #%d %s:%d>' % ((self.__class__.__module__, self.__class__.__name__, self.sock.fileno())+self.sock.getpeername())
+
+ @abc.abstractmethod
+ def parse(self, chunk): pass
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Socketlike:
+ if any('parse' in B.__dict__ and 'getdata' in B.__dict__ for B in C.__mro__):
+ return True
+ return NotImplemented
+
+class _ListenSocket(Socketlike):