这里,在sendQuote方法中,我想发送一个字节数组,但是twisted提供了接受字符串的传输写入方法。如何使用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(your_bytearray)
从中构造一个bytes
实例。在相关问题 更多 >
编程相关推荐