我刚开始用python编码我不能用字符串的加密部分 我正在尝试运行这个简单的服务器客户端代码 (客户端将在raspberry-pi上运行) 服务器:
#!/usr/bin/env python
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
BUFFER_SIZE = 24
conn, addr = server_socket.accept()
print ('Got connection from', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print ("received data:", data)
conn.send(data) # echo
conn.close()
客户:(我有错误)
import socket
client_socket = socket.socket()
client_socket.connect(("192.168.1.4", 8000))
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
client_socket.send(MESSAGE)
data = client_socket.recv(BUFFER_SIZE)
client_socket.close()
print ("received data:", data)
这里的错误=:
File"c.py" line 9, in <module>
client_socket.send<MESSAGE>
typeError:'str' does not support the buffer interface
答案 0 :(得分:0)
在python3中,socket.send()
的接口更改为接受字节而不是字符串。查看Python 3 docuentation和Python 2 documenation之间的区别。
解决方案是在将字符串传递给send()
之前对其进行编码,如下所示:
client_socket.send(MESSAGE.encode())
答案 1 :(得分:0)
在Python中,3x字符串是unicode,它们必须编码为字节以发送到套接字。这一行:
client_socket.send(MESSAGE)
需要更改为:
client_socket.send(MESSAGE.encode('utf-8'))
在服务器端,您可以解码数据以获取字符串。