在这里,我想在sendQuote方法中发送一个字节数组,但是扭曲提供了采用字符串的传输写入方法。我如何使用Twisted发送字节数组作为响应。谢谢。
class QuoteProtocol(protocol.Protocol):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
self.sendQuote()
def sendQuote(self):
#self.file.write(bytearray([0x00, 0x31, 0x34, 0x32, 0x30, 0x30, 0x30, 0x30, 0x31, 0x11, 0x0c, 0x00, 0xfd, 0x09, 0x00, 0x2f, 0xe7, 0x5e, 0x3a, 0x08, 0x3c, 0x00, 0x00, 0x00, 0x49, 0x95]))
self.transport.write("Quote reecevied")
def dataReceived(self, data):
print "Received quote:", data
self.transport.loseConnection()
您为什么要发送bytearray
?Python的本机字符串类型实际上是一个字节数组-一个不变的字节数组。正如您已经观察到的,transport.write
将接受一个字符串。因此,它可以让您发送需要发送的任何字节数组。
如果您bytearray
出于某些充分理由已经在某个实例中包含了一些数据,则可以bytes
使用以下方法轻松地从中构造一个实例:bytes(your_bytearray)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句