Python实现简单http服务器
作者:ordeder 时间:2022-02-04 03:55:01
写一个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.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
浏览器
来源:http://blog.csdn.net/ordeder/article/details/22490373
标签:python,http,服务器
0
投稿
猜你喜欢
Go语言题解LeetCode下一个更大元素示例详解
2024-05-21 10:25:33
python3中的类继承你真的了解吗
2021-06-18 11:23:53
详解利用Python scipy.signal.filtfilt() 实现信号滤波
2022-09-23 21:23:03
Python教程之成员和身份运算符的用法详解
2021-04-19 11:36:56
python实现用户登录系统
2023-10-13 13:17:22
一步步详细讲解vue3配置ESLint
2024-06-05 15:31:55
javascript forEach通用循环遍历方法
2024-04-29 13:19:14
pandas中groupby操作实现
2023-04-15 19:26:56
python3连接mysql获取ansible动态inventory脚本
2024-01-19 23:13:54
javascript实现checkbox全选的代码
2024-04-16 10:38:11
python名片管理系统开发
2022-06-25 13:43:47
Python3中.whl文件创建及使用
2022-11-05 00:17:50
PHP addcslashes()函数讲解
2023-06-10 01:32:33
Python+matplotlib实现简单曲线的绘制
2023-01-05 17:21:27
通过gradio和摄像头获取照片和视频实现过程
2023-07-08 18:02:30
详解git merge 与 git rebase的区别
2023-04-07 20:02:49
Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
2022-12-10 13:55:18
MySQL Index Condition Pushdown(ICP)性能优化方法实例
2024-01-19 20:08:25
Python基于smtplib模块发送邮件代码实例
2022-09-18 11:07:49
z-blog文章摘要图文混排
2009-02-28 13:49:00