背景
我正在努力学习Python3。首先,我将我的一个简单的python2脚本移植到python3。这个脚本非常简单,我在一些问题上陷入困境。在
问题
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()
这是回溯:
^{pr2}$注意事项:
我正在从python2.7.3移植到python3.3
当错误出现时,我会加上更多的错误。在
编辑
尽管[这]是一个很好的答案,但似乎有一个问题-所有发送到服务器的消息前面都有一个b
。我的客户机使用的是python2(我将在今晚晚些时候移植它)-这可能是问题的一部分吗?无论如何,这是相关的代码。在
客户端主循环
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'
在python3.*中,套接字发送和接收的是字节。所以你应该试试:
您应该回顾一下Python 3 guide to Unicode(以及Porting Python 2 Code to Python 3)。
send()
需要字节,但您正在传递一个字符串。在发送字符串之前,您需要调用字符串的encode()
方法,并在打印之前调用所接收字节的decode()
方法。在相关问题 更多 >
编程相关推荐