Christopher Seddon
Christopher Seddon

Reputation: 31

Unable to transfer str to bytes in python 3 messaging service

I can't figure out how to transfer str to bytes in Python 3.

This is the client code:

import socket
import threading

tLock = threading.Lock()
shutdown = False

def receving(name, sock):
    while not shutdown:
        try:
            tLock.acquire()
            while True:
                data, addr = socket.recvfrom(1024).decode()
                print (data)
        except:
            pass
        finally:
            tLock.release()

host = '127.0.0.1'
port = 0

server = ('127.0.0.1',5000)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)

rT = threading.Thread(target=receving, args=("RecvThread",s))
rT.start()

alias = input("Name: ")
message = input(alias + "-> ")
while message != 'q':
    if message != '':
        s.sendto(alias.encode() + ": " + message.encode(), server.encode())
    tLock.acquire()
    message = input(alias + "-> ")
    tLock.release()
    time.sleep(0.2)

shudown = True
rT.join()
s.close()

This is the error I get:

Traceback (most recent call last):
  File "C:/Python34/client fixing.py", line 35, in <module>
    s.sendto(alias.encode() + ": " + message.encode(), server.encode())
TypeError: can't concat bytes to str
>>> 

Upvotes: 1

Views: 322

Answers (2)

snakecharmerb
snakecharmerb

Reputation: 55699

In the line

s.sendto(alias.encode() + ": " + message.encode(), server.encode())

": ", which is a string, is being concatenated with two bytestrings (we know they're bytestrings because .encode() is called on them. This is an error in Python3, but it can be fixed by calling .encode() on the string.

The second parameter to Socket.sendto should be an address. The exact type of the address depends on the socket's family. In this case you have correctly defined address as a tuple (server = ('127.0.0.1',5000)), but you are erroneously calling .encode() on it.

Try changing the line to:

s.sendto(alias.encode() + ": ".encode() + message.encode(), server)

and the error will be fixed.

Upvotes: 0

cdarke
cdarke

Reputation: 44364

This is because ":" is an str (string) object. You could just do b':':

s.sendto(alias.encode() + b": " + message.encode(), server.encode())

but you might find it simpler if you used str.format().encode()

s.sendto("{}: {}".format(alias, message).encode(), server.encode())

Upvotes: 1

Related Questions