Reputation: 468
Here, in sendQuote method I want to send a byte array but twisted provides transport write method which takes string. How can i send a byte array in response using Twisted. Thanks.
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()
Upvotes: 1
Views: 1305
Reputation: 48335
Why do you want to send a bytearray
? Python's native string type is effectively an array of bytes - an immutable one. As you've already observed, transport.write
will accept a string. So it will let you send whatever array of bytes you've got that you need to send.
If you have some data around that is already in a bytearray
instance for some good reason then you can construct a bytes
instance from it using easily: bytes(your_bytearray)
.
Upvotes: 2