Code does not work, error

File "chat.py", line 43, in sendproc sock.sendto (name.get()+':'+text.get(),('localhost',11719)) TypeError: a bytes-like object is required, not 'str' 

here is the code

 # -*- coding: utf-8 -*- import socket from tkinter import * tk=Tk() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind(('localhost',11719)) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,1) text=StringVar() name=StringVar() name.set('HabrUser') text.set('') tk.title('MegaChat') tk.geometry('400x300') log = Text(tk) nick = Entry(tk, textvariable=name) msg = Entry(tk, textvariable=text) msg.pack(side='bottom', fill='x', expand='true') nick.pack(side='bottom', fill='x', expand='true') log.pack(side='top', fill='both',expand='true') def loopproc(): log.see(END) s.setblocking(False) try: message = s.recv(128).decode() log.insert(END,message+'\n') except: tk.after(1,loopproc) return tk.after(1,loopproc) return def sendproc(event): sock.sendto (name.get()+':'+text.get(),('localhost',11719)) text.set('') msg.bind('<Return>',sendproc) msg.focus_set() tk.after(1,loopproc) tk.mainloop() 

    1 answer 1

    Here is the line pointed to by the error:

     sock.sendto (name.get()+':'+text.get(),('localhost',11719)) 

    The error text says:

     TypeError: a bytes-like object is required, not 'str' 

    Which means something like the following:

    Typing error: a byte object is required, not a string

    sendto documentation for the sendto method: socket.sendto

    We see that with the two proposed variants of the call, the first argument is the bytes (and not the string):

     socket.sendto(bytes, address) socket.sendto(bytes, flags, address) 

    From here we conclude that before sending you need to translate your first argument into bytes:

     sock.sendto((name.get()+':'+text.get()).encode(), ('localhost',11719)) 

    If the string can contain not only ascii characters, but also Cyrillic, for example, you need to somehow understand into which encoding the text should be encoded (in general, it depends on what encodings the server side understands). For example, we encode a string in utf-8 encoding:

     sock.sendto((name.get()+':'+text.get()).encode('utf-8'), ('localhost',11719)) 

    On the server side, the s = received_bytes.decode('utf-8') bytes must be decoded from utf-8 into a string, roughly speaking, like this: s = received_bytes.decode('utf-8')