str.encode在数据前面添加一个'b'

时间:2014-02-16 12:00:23

标签: python sockets encode

我通常不会在这里提问,但这对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!'
>>> 

1 个答案:

答案 0 :(得分:4)

嗯,您需要进行以下更改:

在server.py中:

print("Client: ", data.decode())
在client.py中

print(msg.decode())

因为如documentation中所述,unicode.encode()方法输出一个需要转换回.decode()字符串的字节字符串。