0

I am trying to write a socket program using Python. In my client side I have this section:

clientSocket = socket(AF_INET, SOCK_STREAM)         
clientSocket.connect((serverName, serverPort))

linesInBytes = clientSocket.recv(1024)
print(linesInBytes) 

AND in my Server side I have:

connectionSocket, addr = serverSocket.accept()
#Set secret word
word = 'Arkansas'
linesForString = ''     
#Prints out number of letters
for x in word:
    linesForString += '_ '

linesInBytes = linesForString.encode('utf-8')
connectionSocket.send(linesInBytes)

And for some reason when it prints out on the client side, it prints out:

b'_ _ _ _ _ _ _ _ '

And there is no where in the code where I print out a b. Where is this b coming from?? Thank you!

dani
  • 27
  • 3
  • try printing linesInBytes before sending it and see what it contains, please read https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal – JLev Oct 15 '17 at 12:19
  • Also, do you really need the encoding? – JLev Oct 15 '17 at 12:20
  • 1
    In Python `b'....'` represents a byte string (that is, a string of raw bytes with no associated encoding). See e.g. [this question](https://stackoverflow.com/questions/6224052/what-is-the-difference-between-a-string-and-a-byte-string). – larsks Oct 15 '17 at 12:30
  • @JLev bytes must be sent over the connection. Python 3 strings are Unicode so they must be encoded. – Mark Tolonen Oct 15 '17 at 15:26

1 Answers1

0

.decode('utf8') the received data bytes back to a string. Python 3 displays b'' to indicate a byte string vs. a Unicode string.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251