[英]How to send byte array using twisted python
在这里,在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.