Source

networking / src / pyserver.py

Full commit
#-*- coding: utf-8 -*-

import socket
import logging


LOG_FILENAME = 'example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.debug('This message should go to the log file')

"""
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
"""

host = 'localhost' 
port = 8080

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.bind((host, port))
c.listen(1)

while True: 
    csock, caddr = c.accept()
    logging.debug('Accepted') 
    cfile = csock.makefile('rw', 0)
    logging.debug('File created')
    line = cfile.readline().strip()
    
    cfile.write('HTTP/1.0 200 OK\n\n') 
    cfile.write('<html><head><title>Welcome %s!</title></head>' %(str(caddr))) 
    cfile.write('<body><h1>Follow the link...</h1>') 
    cfile.write('All the server needs to do is ') 
    cfile.write('to deliver the text to the socket. ') 
    cfile.write('It delivers the HTML code for a link, ') 
    cfile.write('and the web browser converts it. <br><br><br><br>') 
    cfile.write('<font size="7"><center> <a href="http://python.about.com/index.html">Click me!</a> </center></font>') 
    cfile.write('<br><br>The wording of your request was: "%s"' %(line)) 
    cfile.write('</body></html>')
    logging.debug('Sent')    
    
    cfile.close() 
    csock.close()
    logging.debug('Closed')