python http、模拟服务器返回相关页面(简单案例)
2019-04-15 20:29
295 查看
[code]import socket import re def request_service(new_socket): """为这个客户端返回数据""" #接受浏览器发过来的请求,即http请求 recv_data = new_socket.recv(1024).decode("utf-8") request_lines = recv_data.splitlines() #if len(request_lines) == 0: #request_service(new_socket) file_name = "" #正则表达式 ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0]) if ret: file_name = ret.group(1) if file_name == "/": file_name = "/index.html" print("@"*45) print(file_name) #返回http格式的数据,给浏览器 try: f = open("./html" + file_name, "rb") except : response = "HTTP/1.1 404 NOT FOUND\r\n" response += "\r\n" response += "-----file not found-----" new_socket.send(response.encode("utf-8")) else: html_content = f.read() f.close() #准备发送给浏览器的数据---header response = "HTTP/1.1 200 OK\r\n\r\n" #将response header发给浏览器 new_socket.send(response.encode("utf-8")) #将response body发送给浏览器 new_socket.send(html_content) #关闭套接字 new_socket.colse() def main(): #创建套接字 tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,2) #绑定本地信息 tcp_socket.bind(("", 4545)) #套接字变被动 tcp_socket.listen(128) while True: #等待链接 new_socket, client_addr = tcp_socket.accept() request_service(new_socket) if __name__ =="__main__": main()
相关文章推荐
- 请教一下,http请求彩信数据,抓包返回的协议是MMSE/SMIL协议,现在想模拟彩信服务器返回,java,请问有大神知道这个MMSE协议该怎么构建么?
- Python网络编程 3.1 由简单的TCP服务器、客户端程序分析相关方法
- python3实现TCP协议的简单服务器和客户端案例(分享)
- python创建一个最简单http webserver服务器的方法
- Python模拟HTTPS请求返回HTTP 401 unauthorized错误
- [python相关]BaseHTTPServer -- 基本的 HTTP 服务器
- HTTP协议中GET、POST和HEAD的介绍 2008-05-10 14:15 GET: 请求指定的页面信息,并返回实体主体。 HEAD: 只请求页面的首部。 POST: 请求服务器接受所指定的文
- 实践项目十:爬取百度百科Python词条相关1000个页面数据(慕课简单爬虫实战)
- python创建一个最简单http webserver服务器的方法
- Python模拟HTTPS请求返回HTTP 401 unauthorized错误
- python微型框架flask-post方法接受图片-java模拟http 发送图片到服务器
- 利用python2.7自带的简单的web服务器SimpleHTTPServer实现web页面的访问
- Python爬虫(二十三)_selenium案例:动态模拟页面点击
- Qt HTTP网络相关GET,POST(HTTP 模拟POST 表单(multipartform)最简单和正式的方法)
- ajax简单实例(js内产生xmlHttpRequest,它和servlet交互返回xml显示在页面)
- python简单搭建HTTP Web服务器
- httpClient4.3 模拟Post提交,模拟Post上传文件并解决服务端使用spingMVC时upload.parseRequest(request)解析不到File,Pos简单抓取页面数据
- python---pexpect的pxssh进行模拟ssh登陆返回相关命令信息
- node.js 核心http模块,起一个服务器,返回一个页面
- 【转】python -m SimpleHTTPServer简单服务器命令