egoskeptical
egoskeptical

Reputation: 1113

Simple Python Web Server trouble

I'm trying to write a python web server using the socket library. I've been through several sources and can't figure out why the code I've written doesn't work. Others have run very similar code and claim it works. I'm new to python so I might be missing something simple.

The only way it will work now is I send the data variable back to the client. The browser prints the original GET request. When I try to send an HTTP response, the connection times out.

import socket

##Creates several variables, including the host name, the port to use
##the size of a transmission, and how many requests can be handled at once
host = ''
port = 8080
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(16)
    if data:
        client.send('HTTP/1.0 200 OK\r\n')
        client.send("Content-Type: text/html\r\n\r\n")
        client.send('<html><body><h1>Hello World</body></html>')

    client.close()
    s.close()

Upvotes: 2

Views: 1471

Answers (1)

Graham King
Graham King

Reputation: 5720

You need to consume the input before responding, and you shouldn't close the socket in your while loop:

  1. Replace client.recv(16) with client.recv(size), to consume the request.

  2. Move your last line, s.close() back one indent, so that it is not in your while loop. At the moment you are closing the connection, then trying to accept from it again, so your server will crash after the first request.

Unless you are doing this as an exercise, you should extend SimpleHTTPServer instead of using sockets directly.

Also, adding this line after your create the socket (before bind) fixes any "Address already in use" errors you might be getting.

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Good luck!

Upvotes: 2

Related Questions