如何使用TwistedPython发送字节数组
这里,在sendQuote方法中,我想发送一个字节数组,但twisted提供了采用字符串的传输写入方法。如何使用Twisted发送字节数组作为响应。谢谢如何使用TwistedPython发送字节数组,python,function,bytearray,twisted,Python,Function,Bytearray,Twisted,这里,在sendQuote方法中,我想发送一个字节数组,但twisted提供了采用字符串的传输写入方法。如何使用Twisted发送字节数组作为响应。谢谢 class QuoteProtocol(protocol.Protocol): def __init__(self, factory): self.factory = factory def connectionMade(self): self.sendQuote() def sendQuote(self):
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()
为什么要通过阵列发送
?Python的原生字符串类型实际上是一个字节数组——一个不可变的数组。正如您已经观察到的,transport.write
将接受一个字符串。因此,它将允许您发送任何需要发送的字节数组
如果由于某种原因,您有一些数据已经在bytearray
实例中,那么您可以使用bytes(您的bytearray)
轻松地从中构造一个bytes
实例