Python은 간단한 http 서버를 구현합니다.

不言
풀어 주다: 2018-04-23 16:09:04
원래의
4511명이 탐색했습니다.

이 글은 주로 Python으로 간단한 http 서버를 구현하는 방법을 자세히 소개하며, 관심 있는 친구들은 참고할 수 있습니다.

간단한 http 서버 기능을 구현하기 위한 Python 스크립트 작성:

1. 브라우저의 주소: 172.20.52.163:20014

2. 서버는 브라우저로부터 요청을 받은 후 로컬 index.html 파일의 내용을 읽고 이를 브라우저로 다시 보냅니다

코드 구현

서버 .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

<html> 
 <head> 
   <title>Python Server</title> 
 </head> 
 <body> 
  <h1>Hello python</h1> 
  <p>Welcom to the python world</br> 
 </body> 
</html>
로그인 후 복사

Test

테스트 결과:

root@cloud2:~/slp/pythonLearning/socket# ./server_v1.py 
connect by (&#39;172.20.52.110&#39;, 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

관련 추천:

Python은 브라우저를 무작위로 호출하여 웹 페이지를 여는 방법을 구현합니다

Python은 Excel에 데이터를 쓰는 순서와 배열을 사용자 정의하는 방법을 구현합니다

위 내용은 Python은 간단한 http 서버를 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!