str.encode adds a 'b' to the front of data

被刻印的时光 ゝ 提交于 2020-01-23 08:28:05

问题


I don't normally ask questions here but this isn't something easy to just Google.

Basically, I'm trying to send a bit of data to my server from a client. It's a very simple client/server setup.

I'll just show you the code and output. Any help is appreciated!

server.py code

#!/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 output

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 code

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 output

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:


well, you need to do the following changes:

in server.py:

print("Client: ", data.decode())

in client.py:

print(msg.decode())

because as explained in the documentation, the unicode.encode() method outputs a byte string that needs to be converted back to a string with .decode().



来源:https://stackoverflow.com/questions/21810776/str-encode-adds-a-b-to-the-front-of-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!