背景
我正在尝试学习Python 3。为了快速启动,我正在将我的一个简单的Python 2脚本移植到Python 3。这个脚本非常简单,我被困在了几个问题上。
The Issues
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备注:
我正在从Python2.7.3移植到Python3.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 replyShell填充服务器
HOST: not_real.local
PORT: 2468
Socket Created
Socket Bind Complete
Socket now listening
Connected with 25.**.**.***:64203
b'xxmbabanexx : Hello'发布于 2013-03-24 02:39:22
您应该检查Python 3 Unicode指南 (以及将Python 2代码移植到Python 3)。send()需要字节,但是您要给它传递一个字符串。您需要在发送字符串之前调用字符串的encode()方法,并在打印它们之前调用接收到的字节的decode()方法。
发布于 2013-03-24 02:39:05
在python3.*中,套接字发送和接收的是字节。所以你应该试试:
connection.send(b"Welcome to the server. Type something and hit enter\n")https://stackoverflow.com/questions/15594534
复制相似问题