Sending http headers with python

后端 未结 2 2036
无人共我
无人共我 2021-02-09 06:59

I\'ve set up a little script that should feed a client with html.

import socket

sock = socket.socket()
sock.bind((\'\', 8080))
sock.listen(5)
client, adress = s         


        
2条回答
  •  南旧
    南旧 (楼主)
    2021-02-09 08:04

    The response header should include a response code indicating success. Before the Content-Type line, add:

    client.send('HTTP/1.0 200 OK\r\n')
    

    Also, to make the test more visible, put some content in the page:

    client.send('

    Hello World')

    After the response is sent, close the connection with:

    client.close()
    

    and

    sock.close()
    

    As the other posters have noted, terminate each line with \r\n instead of \n.

    Will those additions, I was able to run successful test. In the browser, I entered localhost:8080.

    Here's all the code:

    import socket
    
    sock = socket.socket()
    sock.bind(('', 8080))
    sock.listen(5)
    client, adress = sock.accept()
    
    print "Incoming:", adress
    print client.recv(1024)
    print
    
    client.send('HTTP/1.0 200 OK\r\n')
    client.send("Content-Type: text/html\r\n\r\n")
    client.send('

    Hello World') client.close() print "Answering ..." print "Finished." sock.close()

提交回复
热议问题