我通常在这里不问问题,但这对Google而言并不容易.
基本上,我正在尝试从客户端向服务器发送一些数据.这是一个非常简单的客户端/服务器设置.
我只向您显示代码和输出.任何帮助表示赞赏!
server.py代码
#!/usr/bin/env python
import socket
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1: #always listening
client, address = s.accept() #gets client
data = client.recv(size) #gets message
if data:
print("Client: ", data)
client.close() #close, and listen for new client
server.py输出
Python 3.3.1 (v3.3.1:d9893d13c628, Apr 6 2013, 20:30:21) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Client: b'Hello World!'
client.py代码
import socket
msg = 'Hello World!'
msg = str.encode(msg, 'utf-8')
clientsocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientsocket.connect(('brandon-pc4', 50000))
clientsocket.send(msg)
print(msg)
client.py输出
Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:12:08) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
b'Hello World!'
>>>
解决方法:
好,您需要进行以下更改:
在server.py中:
print("Client: ", data.decode())
在client.py中:
print(msg.decode())
因为如documentation中所述,unicode.encode()方法输出一个字节字符串,需要使用.decode()将其转换回字符串.