[Top-Down Approach] Assignment 1: WebServer [Python]

Today I complete Socket Programming Assignment 1 Web Server

Here is the code:

#!/usr/bin/python2.7
# Program: Web Server
# Date: 2016-03-19
# Author: brant-ruan
# P.S.

from socket import *

serverPort = 12000

# Prepare a server socket
serverSocket = socket(AF_INET, SOCK_STREAM) # create socket
serverSocket.bind(('', serverPort)) # bind socket to specific port
serverSocket.listen(1) # listen connections

endFlag = '\x0d\x0a'
# Status
statusOK = 'HTTP/1.1 200 OK' + endFlag
statusErr = 'HTTP/1.1 404 Not Found' + endFlag
# HTTP header
header = 'Content-Type: text/html; charset=utf-8' + endFlag
while True:
    print 'Ready to serve...'
    (connectionSocket, addr) = serverSocket.accept() # create another connection socket
    try:
        message = connectionSocket.recv(1024) # receive messages
        filename = message.split()[1]   # fetch the filename client asks
        f = open(filename[1:], 'r')
        outputdata = f.read()
        f.close()
        connectionSocket.send(statusOK)  # 200 OK
        connectionSocket.send(header)   # header line (optional or not?)
        connectionSocket.send(endFlag)   # end of header
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i])  # the whole file asked by client
        print 'OK'
        connectionSocket.close() # close the connection
    except IOError:
        print 'ERROR'
        connectionSocket.send(statusErr)
        connectionSocket.send(endFlag)
        connectionSocket.close()

serverSocket.close()

P.S.
I write a simple html file named test.html in the same directory where the webserver.py is located.
And we use DHCP to share only one external IP address.
Supposing that my internal IP address is 192.168.1.101, then I can input [http://192.168.1.101:12000/test.html] in the address label of browser to test.
However hosts in the external network can not communicate with your server process.
Here are two solutions (I think there at least these two solutions):

  1. Configure your router and map the 12000 port to your private IP(Your internal IP address 192.168.1....).
  2. Configure your router and specify your host as the DMZ host.

Whichever methods you use, now you can input [http://YOUR-EXTERNAL-IP-ADDRESS:PORT-ID/test.html] to your browser.


Here are some thoughts after finishing the experiment:

[Top-Down Approach] Assignment 1: WebServer [Python]

bingo!

上一篇:修改session垃圾回收几率


下一篇:JBPM学习(五):流程变量