Reputation: 1471
I am following the Twisted tutorial (see bottom of here)
I am trying to connect to the chat server but i keep getting the following error
File "/Users/kevin/anaconda3/lib/python3.6/site-packages/twisted/internet/tcp.py", line 1073, in doRead
protocol.makeConnection(transport)
File "/Users/kevin/anaconda3/lib/python3.6/site-packages/twisted/internet/protocol.py", line 510, in makeConnection
self.connectionMade()
File "twisted_chat.py", line 12, in connectionMade
self.sendLine("What's your name?") <------------- This line
File "/Users/kevin/anaconda3/lib/python3.6/site-packages/twisted/protocols/basic.py", line 635, in sendLine
return self.transport.write(line + self.delimiter)
builtins.TypeError: must be str, not bytes
The code that seems to be triggering this error is
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class Chat(LineReceiver):
def __init__(self, users):
self.users = users
self.name = None
self.state = "GETNAME"
def connectionMade(self):
self.sendLine("What's your name?") <------- This line
def connectionLost(self, reason):
if self.name in self.users:
del self.users[self.name]
I am a bit puzzled since "What's your name?"
is clearly a string, not bytes. I am using Python 3.6 with Twisted 17.9.0
EDIT: I tried running the same code in python 3.4 and i got builtins.TypeError: Can't convert 'bytes' object to str implicitly
I've been searching but can't seem to find an solution to the problem. Does anyone know how I can fix this?
Upvotes: 4
Views: 1187
Reputation: 5107
Your code should run fine in Python/Anaconda v2 but not in v3 unless you've left some code out. For Py v3+, use either:
self.sendLine( b"What's your name?" )
self.sendLine( "What's your name?".encode('utf8') )
As you can see in docs for LineReceiver.sendLine
the argument must be type bytes
.
Upvotes: 6