本文主要内容

  • 文件打开方式,文本与二进制区别
  • 用类封装简单的Web静态服务器

0x01 文件打开方式,文本与二进制区别

文本文件,操作系统会对\n进行一些隐式变换,因此文本文件直接跨平台使用会出问题。
在Windows下,写入\n时,操作系统会隐式的将\n转换为\r\n,再写入到文件中;读的时候,会把\r\n隐式转化为\n,再读到变量中。
在Linux下,写入’\n’时,操作系统不做隐式变换。
二进制文件,操作系统不会对\n进行隐式变换,很多二进制文件(如电影、图片等)可以跨平台使用。

  • 以二进制形式写入wb文件
1
2
3
f= open("wb","wb")
f.write(b"hello\nhello")
f.close()
  • 以文本方式写入w文件
1
2
3
f= open("w","w")
f.write("hello\nhello")
f.close()

使用Notepad++打开wb和w文件显示并无任何区别

  • 分别读取观察,发现windows中文本读取将\n变为\r\n
1
2
with open("wb","rb") as f:
print(f.read())
b'hello\nhello'
1
2
with open("w","rb") as f:
print(f.read())
b'hello\r\nhello'

0x02 python使用类封装Web静态服务器

  • 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# coding: utf-8
import socket

from multiprocessing import Process

import re

HTML_ROOT_DIR = "./html"

class HTTPserver(object):
"""init"""
def __init__(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)


def start(self):
self.server_socket.listen(128)
"""多进程处理请求"""
while True:
client_socket, client_address = self.server_socket.accept()
print("[%s,%s]用户连接上了" % client_address)
handle_client_process = Process(target=self.handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close()


def handle_client(self,client_socket):
"""处理客户端请求"""
# 获取客户端数据
request_data = client_socket.recv(2048)
print("request data:",request_data)

# 处理请求数据
request_lines = request_data.splitlines()
for line in request_lines:
print(line)

# "GET / HTTP/1.1"
request_start_line = request_lines[0]
file_name = re.match(r"\w+ +(/[^ ]*)",request_start_line.decode("utf-8")).group(1)

if "/" == file_name:
file_name= "/index.html"
# 打开文件
try:
file = open(HTML_ROOT_DIR+file_name,"rb")
except IOError:
# 构造响应数据
response_start_line = "HTTP/1.1 404 Not Found\r\n"
response_headers = "Server: My testserver\r\n"
response_body = "file is not found!"
else:
file_data = file.read()
file.close()
# 构造响应数据
response_start_line = "HTTP/1.1 200 0k\r\n"
response_headers = "Server: My testserver\r\n"
response_body = file_data.decode("utf-8")


response = response_start_line + response_headers+ "\r\n"+ response_body
print("response:",response)

# 向客户端发送数据
client_socket.send(bytes(response,"utf-8"))
# 关闭客户端连接
client_socket.close()

def bind(self,port):
self.server_socket.bind(("", port))


def main():
http_server = HTTPserver()
http_server.bind(8000)
http_server.start()
if __name__ == "__main__":
main()