Python实现简单http服务器

Python实现简单http服务器,第1张

概述写一个python脚本,实现简单的http服务器功能:1.浏览器中输入网站地址:172.20.52.163:20014

写一个python脚本,实现简单的http服务器功能:

1.浏览器中输入网站地址:172.20.52.163:20014

2.server接到浏览器的请求后,读取本地的index.HTML文件的内容,回发给浏览器

代码实现

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

<HTML>  <head>    <Title>Python Server</Title>  </head>  <body>   <h1>Hello python</h1>   <p>Welcom to the python world</br>  </body> </HTML> 

测试

测试结果:

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

浏览器

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

您可能感兴趣的文章:Python通过命令开启http.server服务器的方法python探索之BaseHTTPServer-实现Web服务器介绍Python探索之实现一个简单的HTTP服务器Python实现简单的HttpServer服务器示例Python搭建HTTP服务器和FTP服务器Python内置的HTTP协议服务器SimpleHTTPServer使用指南使用Python来编写HTTP服务器的超级指南python创建一个最简单http webserver服务器的方法用Python实现一个简单的能够上传下载的HTTP服务器使用nodejs、Python写的一个简易HTTP静态文件服务器 总结

以上是内存溢出为你收集整理的Python实现简单http服务器全部内容,希望文章能够帮你解决Python实现简单http服务器所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1204397.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存