2017-02-26 88 views
-1

我有這個PROGRAMM,但對我說的標題錯誤,我想我必須把東西應用UTF-8,但我不知道在哪裏,如何解決TypeError:需要類字節對象,而不是'str'?

#!/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 
+2

可能重複[TypeError:需要類似字節的對象,而不是'str'](http://stackoverflow.com/questions/35777639/typeerror-a-bytes-like-object-is-required-not -str) – Idos

回答

1

send希望如何bytes ,而不是string。 Python 3中的字符串是unicode,你必須指定字符串應該如何轉換爲字節。首先使用類似socket.send("some string".encode("utf-8"))的字符串將字符串轉換爲bytes

相關問題