Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!'
>>> 
like image 313
BrandonMXB Avatar asked Feb 16 '14 12:02

BrandonMXB


1 Answers

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().

like image 144
zmo Avatar answered Nov 04 '22 02:11

zmo