背景
我正在尝试学习Python 3.要快速启动,我将一个简单的Python 2脚本移植到Python 3.脚本是极简单而且我遇到了一些问题。
问题
TypeError: 'str' does not support the buffer interface
我使用socket .send()
命令发送服务器的欢迎消息。当服务器尝试发送它时,我收到上述错误。这是相关的代码。
def clientthread(connection):
#Sending message to connected client
#This only takes strings (words
connection.send("Welcome to the server. Type something and hit enter\n")
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = connection.recv(1024)
if not data:
break
connection.sendall(data)
print (data)
connection.close()
这是追溯:
Unhandled exception in thread started by <function clientthread at 0x1028abd40>
Traceback (most recent call last):
File "/Users/*****/Desktop/Coding/Python 3/Sockets/IM Project/Server/Server v3.py", line 41, in clientthread
connection.send("Welcome to the server. Type something and hit enter\n")
TypeError: 'str' does not support the buffer interface
备注:
我正在从Python 2.7.3移植到Python 3.3
我会在出现错误时添加更多错误。
修改
尽管[这个]是一个很好的答案,但似乎存在问题 - 发送到服务器的所有邮件都以b
开头。我的客户端是Python 2(我将在今晚稍后移植) - 这可能是问题的一部分吗?无论如何,这是相关的代码。
客户主要循环
while True:
#Send some data to the remote server
message = raw_input(">>> ")
try:
#set the whole string
s.sendall(USER + " : " + message)
except socket.error:
#Send Failed
print "Send failed"
sys.exit()
reply = s.recv(1024)
print reply
Shell Stuff Server
HOST: not_real.local
PORT: 2468
Socket Created
Socket Bind Complete
Socket now listening
Connected with 25.**.**.***:64203
b'xxmbabanexx : Hello'
答案 0 :(得分:1)
您应该查看 Python 3 guide to Unicode (以及Porting Python 2 Code to Python 3)。 send()
需要字节,但是你传递的是字符串。您需要在发送之前调用字符串的encode()
方法,并在打印之前接收字节的decode()
方法。
答案 1 :(得分:0)
在python3。*中,什么套接字发送和接收是字节。所以你应该尝试:
connection.send(b"Welcome to the server. Type something and hit enter\n")