Reputation: 45
I am trying to get my python code to work on python 3. In python 2 it worked properly but when i put it in python 3 it recieves the wrong text from the socket. In python 2 it recieved stop
but in python 3 it recieves b'stop'
. And i can't find out why.
Mycode:
import socket
import sys
import subprocess
HOST = '192.168.176.71'
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket created')
try:
s.bind((HOST, PORT))
except socket.error as err:
print('Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1])
sys.exit()
print('Socket Bind Success!')
s.listen(10)
print('Socket is now listening')
while 1:
conn, addr = s.accept()
print('Connect with ' + addr[0] + ':' + str(addr[1]))
buf = conn.recv(4096)
if buf == "stop":
print("stoping")
exit()
print(buf)
s.close()
Upvotes: 0
Views: 48
Reputation: 12027
'stop'
is a string and b'stop'
is a bytes object not a string.
The documentation of python 3 for recv()
says:
Receive data from the socket. The return value is a bytes object representing the data received.
The documentation for python 2 recv()
says:
The return value is a string representing the data received.
So the behaviour is correct in python 2 you receive a string but in python 3 you receive bytes. So if you want this as a string then you need to decode it.
data = bytes('stop'.encode())
print(data)
print(data.decode())
print(data == 'stop')
print(data.decode() == 'stop')
OUTPUT
b'stop'
stop
False
True
Upvotes: 1