Home>Article>Backend Development> Python implements a simple http server

Python implements a simple http server

不言
不言 Original
2018-04-23 16:09:04 4495browse

This article mainly introduces Python to implement a simple http server in detail, which has certain reference value. Interested friends can refer to

Write a python script to implement a simple http server. Function:

1. Enter the website address in the browser: 172.20.52.163:20014

2. After the server receives the request from the browser, it reads the contents of the local index.html file. Post back to the browser

Code implementation

server.py

#!/usr/bin/python import socket import signal import errno from time import sleep def HttpResponse(header,whtml): f = file(whtml) contxtlist = f.readlines() context = ''.join(contxtlist) response = "%s %d\n\n%s\n\n" % (header,len(context),context) return response def sigIntHander(signo,frame): print 'get signo# ',signo global runflag runflag = False global lisfd lisfd.shutdown(socket.SHUT_RD) strHost = "172.20.52.163" HOST = strHost #socket.inet_pton(socket.AF_INET,strHost) PORT = 20014 httpheader = '''''\ HTTP/1.1 200 OK Context-Type: text/html Server: Python-slp version 1.0 Context-Length: ''' lisfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM) lisfd.bind((HOST, PORT)) lisfd.listen(2) signal.signal(signal.SIGINT,sigIntHander) runflag = True while runflag: try: confd,addr = lisfd.accept() except socket.error as e: if e.errno == errno.EINTR: print 'get a except EINTR' else: raise continue if runflag == False: break; print "connect by ",addr data = confd.recv(1024) if not data: break print data confd.send(HttpResponse(httpheader,'index.html')) confd.close() else: print 'runflag#',runflag print 'Done'

index.html

  Python Server 

Hello python

Welcom to the python world

Test

Test result:

root@cloud2:~/slp/pythonLearning/socket# ./server_v1.py connect by ('172.20.52.110', 6096) GET / HTTP/1.1 Host: 172.20.52.163:20014 Connection: keep-alive Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36 Accept-Encoding: gzip,deflate,sdch Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

Browser

Related recommendations:

Python implements a random call Open the web page in the browser

Python's method to implement custom order and arrangement of writing data to Excel

##

The above is the detailed content of Python implements a simple http server. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn