简体   繁体   中英

python 3 http socket not working

My code:

import socket

host = ''
port = 8090
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
    client, address = s.accept()
    #data = client.recv(size)


    data= "ok"

    if data:
        client.send(bytes('HTTP/1.0 200 OK<CRLF>', 'UTF-8'))
        client.send(bytes("Content-Type: text/html<CRLF><CRLF>", 'UTF-8'))
        client.send(bytes('<html><body><h1>Hello World</body></html>', 'UTF-8'))
    client.close()

for some reason whenever i visit: http:localhost:8090 google chrome returns:

"The webpage at http:localhost:8090 might be temporarily down or it may have moved permanently to a new web address."

I looked up tons of examples, and I have no clue why this is not working

I am running python 3.3 on windows 7, thankyou.

Your <CRLF> characters should be \\r\\n in python. If you then put the .recv back in it works:

import socket

host = ''
port = 8090
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
    client, address = s.accept()
    data = client.recv(size)

    if data:
        client.send(bytes('HTTP/1.0 200 OK\r\n', 'UTF-8'))
        client.send(bytes("Content-Type: text/html\r\n\r\n", 'UTF-8'))
        client.send(bytes('<html><body><h1>Hello World</body></html>', 'UTF-8'))
    client.close()

Python uses the backslash \\ character for escaping in strings. See http://docs.python.org/2/reference/lexical_analysis.html#strings for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM