How can I remove 'TypeError: a bytes-like object is required, not 'str''

How can I remove 'TypeError: a bytes-like object is required, not 'str''

import sys
from socket import *

ECHO_PORT = 50000 + 7
BUFSIZE = 1024


def main():
    if len(sys.argv) < 2:
        usage()
    if sys.argv[1] == '-s':
        server()
    elif sys.argv[1] == '-c':
        client()
    else:
        usage()

def usage():
    sys.stdout = sys.stderr
    print('Usage : udpecho -s [port]            (server)')
    print('or:     udpecho -c host [port] <file (client)')
    sys.exit(2)

def server():
    if len(sys.argv) > 2:
        port = eval(sys.argv[2])
    else:
        port = ECHO_PORT

    s = socket(AF_INET, SOCK_DGRAM)  ## UDP = SOCK_DGRAM, TCP = SOCK_STREAM
    s.bind(('', port))
    print('udp echo server ready')

    while 1:
        data, addr = s.recvfrom(BUFSIZE)
        print('server received %r from %r'%(data, addr))
        s.sendto(data, addr)


def client():
    if len(sys.argv) < 3:
        usage()

    host = sys.argv[2]

    if len(sys.argv) > 3:
        port = eval(sys.argv[3])
    else:
        port = ECHO_PORT

    addr = host, port
    s = socket(AF_INET, SOCK_DGRAM)
    s.bind(('', 0))
    print('udp echo client ready, reading stdin')

    while 1:
        line = sys.stdin.readline()
        if not line:
            break
        s.sendto(line, addr)

        data, fromaddr = s.recvfrom(BUFSIZE)
        print('client received %r from %r'%(data, fromaddr))
main()

我想用 python 制作客户端和服务器程序。 但是这个错误困扰着我

Traceback (most recent call last):
  File "udp_echo.py", line 98, in <module>
    main()
  File "udp_echo.py", line 32, in main
    client()
  File "udp_echo.py", line 89, in client
    s.sendto(line, addr.encode())
TypeError: a bytes-like object is required, not 'str'

我尝试了很多方法来删除此错误代码,但我没有任何想法。 有人告诉我,这个问题是 python 版本的原因,但我不知道如何解决这个问题。 我怎样才能删除这个错误代码?

s.sendto(line.encode('utf8'), addr) 将其转换为 utf8 字节(可能是你想要的)