【发布时间】:2013-03-24 02:32:58
【问题描述】:
背景
我正在尝试学习 Python 3。为了快速入门,我将我的一个简单的 Python 2 脚本移植到 Python 3。该脚本非常非常简单,但我遇到了一些问题。
问题
TypeError: 'str' does not support the buffer interface
我使用套接字.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
我会在出现错误时添加更多错误。
编辑
尽管 [this] 是一个很好的答案,但似乎存在一个问题 - 所有发送到服务器的消息都以 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 服务器
HOST: not_real.local
PORT: 2468
Socket Created
Socket Bind Complete
Socket now listening
Connected with 25.**.**.***:64203
b'xxmbabanexx : Hello'
【问题讨论】:
-
“我会在出现错误时添加更多错误”:您应该为每个特定问题打开新问题。
标签: python