当前位置: 移动技术网 > IT编程>脚本编程>Python > python实现静态web服务器

python实现静态web服务器

2019年09月06日  | 移动技术网IT编程  | 我要评论

八年级上册语文,图形创意课件,在线尺子刻度

http协议简介

http请求

1:浏览器首先向服务器发送http请求,请求包括:

方法:get还是post,get仅请求资源,post会附带用户数据;
路径:/full/url/path;
域名:由host头指定:host: www.sina.com以及其他相关的header;
如果是post,那么请求还包括一个body,包含用户数据

2:服务器向浏览器返回http响应,响应包括:

响应代码:200表示成功,3xx表示重定向,4xx表示客户端发送的请求有错误,5xx表示服务器端处理时发生了错误;
响应类型:由content-type指定;
以及其他相关的header;
通常服务器的http响应会携带内容,也就是有一个body,包含响应的内容,网页的html源码就在body中。

3:如果浏览器还需要继续向服务器请求其他资源,比如图片,就再次发出http请求,重复步骤1、2。

web采用的http协议采用了非常简单的请求-响应模式,从而大大简化了开发。当我们编写一个页面时,我们只需要在http请求中把html发送出去,不需要考虑如何附带图片、视频等,浏览器如果需要请求图片和视频,它会发送另一个http请求,因此,一个http请求只处理一个资源(此时就可以理解为tcp协议中的短连接,每个链接只获取一个资源,如需要多个就需要建立多个链接)

http格式

每个http请求和响应都遵循相同的格式,一个http包含header和body两部分,其中body是可选的。
http协议是一种文本协议,所以,它的格式也非常简单。

1 http get请求的格式:

get /path http/1.1
 header1: value1
 header2: value2
 header3: value3

每个header一行一个,换行符是\r\n。

2 http post请求的格式:

post /path http/1.1
 header1: value1
 header2: value2
 header3: value3

 body data goes here...

3 http响应的格式:

200 ok
 header1: value1
 header2: value2
 header3: value3

 body data goes here...

http响应如果包含body,也是通过\r\n\r\n来分隔的。
请再次注意,body的数据类型由content-type头来确定,如果是网页,body就是文本,如果是图片,body就是图片的二进制数据。
当存在content-encoding时,body数据是被压缩的,最常见的压缩方式是gzip,所以,看到content-encoding: gzip时,需要将body数据先解压缩,才能得到真正的数据。压缩的目的在于减少body的大小,加快网络传输。

demo:静态web服务器

import socket
import re
import time


def service_client(new_socket):
 """为这个客户端服务"""

 # 1.接收浏览器发送过来的请求,即http请求
 # get / http/1.1
 # --------
 request = new_socket.recv(1024).decode('utf-8')

 # 判断客户端意外断开链接返回空字符串
 if not request:
  # 关闭套接字并退出
  new_socket.close()
  print("==="*30)
  return

 # 分隔套接字
 request_lines = request.splitlines()
 print()
 print(">"*20)
 print(request_lines)

 file_name = ""
 ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
 if ret:
  file_name = ret.group(1)
  if file_name == "/":
   file_name = "/"

 # 2.返回http格式数据 给浏览器
 try:
  f = open("./html" + file_name, "rb")
 except:
  response = "http/1.1 404 not found\r\n"
  response += "content-type:text/html;charset=utf-8\r\n"
  response += "\r\n"
  response += "<h1>404 not found <br> 没有发现所请求资源</h1>"
  response += str(time.strftime('%y-%m-%d %h:%m:%s', time.localtime(time.time())))
  new_socket.send(response.encode('utf-8'))
 else:
  html_content = f.read()
  f.close()
  # 2.1准备发送给浏览器的数据---header
  response = "http/1.1 200 ok\r\n"
  response += "\r\n"
  # 2.2准备发送给浏览器的数据 ---body
  # 将response header发送给浏览器
  new_socket.send(response.encode("utf-8"))
  # 将response body发送给浏览器
  new_socket.send(html_content)

 # 关闭套接字
 new_socket.close()


def main():
 """用来完成整体的控制"""
 # 1.创建套接字
 tcp_server_socket = socket.socket(socket.af_inet, socket.sock_stream)
 # 端口复用
 tcp_server_socket.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1)
 # 2.绑定
 tcp_server_socket.bind(("", 7890))
 # 3.变为套接字
 tcp_server_socket.listen(128)

 while true:
  # 4.等待客户端的链接
  new_socket, client_addr = tcp_server_socket.accept()

  print(client_addr)

  # 5.为这个客户端服务
  service_client(new_socket)

 # 关闭监听套接字
 tcp_server_socket.close()


if __name__ == '__main__':
 main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网