如何使用twisted python发送字节数组

2024-10-02 16:27:44 发布

您现在位置: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()

Tags: 方法字符串selfdata字节factorydeftwisted
1条回答
网友
1楼 · 发布于 2024-10-02 16:27:44

为什么要发送bytearray?Python的本机字符串类型实际上是一个字节数组—一个不可变的数组。正如您已经看到的,transport.write将接受一个字符串。所以它可以让你发送你需要发送的任何字节数组。在

如果您有一些数据已经存在于bytearray实例中,那么您可以轻松地使用bytes(your_bytearray)从中构造一个bytes实例。在

相关问题 更多 >