实现多并发的web服务端
import spcket
from threading import Thread server=socket.socket() #实例化socket对象 server.bind(('127.0.0.1',10086)) #绑定地址及应用端口号 server.listen() #建立连接 def feedback(conn): client_msg=conn.recv(1024) #接收连接请求
print(client_msg) #打印请求内容 path=client_msg.split(' ')[0].split(' ')[1]
#获取请求的文件 if path=='/':
conn.send(b'HTTP/1.1 200 ok ')
#响应 协议版本:HTTP/1.1 状态码:200 状态码的描述 回车符换行符 with open('dome.html','rb')as f_html: data=f_html.read() conn.send(data)
#发送请求文件 conn.close() if path=='/dome.css':
conn.send(b'HTTP/1.1 200 ok ') with open('dome.css','rb')as f_css: data=f_css.read() conn,send(data) conn.close() if path =='/dome.js':
conn.send(b'HTTP/1.1 200 ok ') with open('dome.js','rb')as f_js: data=f_js.read() conn.send(data) conn.close() if path=='/background.jpg':
conn.send(b'HTTP/1.1 200 ok ') with open('background.jpg','rb')as f_bg: data=f_bg.read() conn.send(data) conn.close() if path=='/favicon.ico':
conn.send(b'HTTP/1.1 200 ok ') with open('favicon.ico','rb')as f_ico: data=f_ico.read() conn.send() conn.close() while True: conn,addr=server.accept()
#获取连接 t=Thread(target=fun,args=(conn,))
#设置线程 t.start()
#开启线程
HTTP协议
http协议使超文本传输协议,位于osi七层的应用层,协议规定的就是请求与响应双方的一个消息格式,请求(请求行,请求头,空行 请求数据)
HTTP请求格式
请求方法 空格 URL(即请求文件路径) 空格 协议版本 回车符 换行符 ps:(请求行)
头部字段名 冒号 值 回车符 换行符 ps:(请求头部 可能会有多行)
回车符 换行符
请求数据
HTTP响应格式
协议版本 空格 状态码 空格 状态码描述 回车符 换行符 ps:(状态行)
头部字段名 冒号 值 回车符 换行符 ps:(响应头部 可能会多行)
回车符 换行符
响应正文(.htm .css .js等)
请求方法:get post put delete patch options connect gead
状态码:1xx 待处理
2xx 成功
3xx 待跳转
4xx 语法错误
5xx 服务器错误