我如何解决TypeError:需要一个类似字节的对象,而不是'str'?

时间:2017-02-26 11:17:50

标签: python

我有这个程序,但它告诉我标题上的错误,我想我必须把东西用于申请utf-8,但我不知道在哪里或如何

 #!/usr/bin/python3

import socket

status = 0

mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
mySocket.bind(('localhost', 1234))



mySocket.listen(5)

while True:
    print('Waiting for connections')
    (recvSocket, address) = mySocket.accept()
    print('HTTP request received:')
    print(recvSocket.recv(1024))
    request = recvSocket.recv(1024)

    slot = request.split(' ')

    try:
        num = int(slot[1][1:])
    except ValueError:
        msg = ("Asegurese que su URL contiene un numero al final. Ejemplo: localhost:1234/56")
        recvSocket.send("HTTP/1.1 200 OK\r\n\r\n" + "<html><body>" + msg + "</body></html>" + "\r\n")
        status = 0

1 个答案:

答案 0 :(得分:1)

send预计bytes,而不是string。 Python 3中的字符串是unicode,您必须指定字符串应如何转换为字节。使用socket.send("some string".encode("utf-8"))之类的内容首先将字符串转换为bytes