如何使用Twisted Python 发送字节数组
在这个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()
1 个回答
2
你为什么想发送一个 bytearray
呢?其实,Python 自带的字符串类型本质上就是一个字节数组,只不过它是不可变的。正如你已经注意到的,transport.write
可以接受字符串。所以,它可以让你发送任何你需要发送的字节数组。
如果你手头有一些数据,已经是 bytearray
类型,那是有原因的,你可以很简单地用 bytes(your_bytearray)
来从中构建一个 bytes
实例。