I am trying to implement a very basic web-server-like application with Python, this is my current code:
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print 'Server is now running...'
while 1:
connectionSocket, addr = serverSocket.accept()
connectionSocket.sendall('''
HTTP/1.0 200 OK\r\n
Content-Type:text/html\r\n
Connection:close\r\n
\r\n
<!DOCTYPE html>
<head><title>Lab sign-up - AntonX Server</title></head>
<h1>Lab Sign-up</h1>
<table>
<form action=\"localhost:12000\" method=\"GET\">
<tr><td>Time</td><td>Name</td></tr>
<tr><td>1 PM</td><td><input type=\"text\" name=\"time_1\"></td></tr>
<tr><td>2 PM</td><td><input type=\"text\" name=\"time_2\"></td></tr>
<tr><td>3 PM</td><td><input type=\"text\" name=\"time_3\"></td></tr>
<tr><td>4 PM</td><td><input type=\"text\" name=\"time_4\"></td></tr>
<tr><td>5 PM</td><td><input type=\"text\" name=\"time_5\"></td></tr>
<tr><td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"Steal this spot!\"></tr>
</form></table>
</html>\r\n
''')
connectionSocket.close()
Problem is…when I navigate to localhost:12000, I get an error 101: Connection has been reset. Why is that?
The data you are sending back has lots of extra spaces and newline characters.
For example,
will send the string
In other words, you are getting a mixture of new lines that you have explicitly included with \r\n, and newlines that are naturally in your source code.
This code works on my web browser.
(However, this is not a very nice way of writing web servers in Python!)
You may wish to look at various built in functions in Python to help with this kind of code, perhaps starting at SimpleHTTPServer.