刚买了个树莓派,用socket试一下文件服务器。错误望纠正!
创建文件:
touch httpserver.py
touch config.py
mkdir data
cd data
mkdir public
touch index.html error.html news.html
config.py:
#httpapi
httpapidir = "data/"
httpapiall = "data/"
port = 80
httpserver.py 这里需要sudo
import socket
import threading
import warnings
import os
from datetime import datetime
import logging
logging.basicConfig(filename='data/server_'+str(datetime.now().strftime("%Y-%m-%d"))+'.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
print("[DF httpapi] Starting ...")
import config
warnings.filterwarnings("ignore")
def log(message):
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
logging.info(f"{current_time} - {message}")
def sponse(data):
response_line = "HTTP/1.1 200 OK\r\n"
response_header = "Server: PWS1.0\r\n"
response_body = data
response_data = (response_line + response_header + "\r\n").encode("utf-8") + response_body
return response_data
def handle_client_request(new_socket):
recv_client_data = new_socket.recv(4096)
if len(recv_client_data) == 0:
#log("User closed the web")
print("[static http server] User closed the web")
new_socket.close()
return
recv_client_content = str(recv_client_data)
#log("Recv_client_content: " + recv_client_content)
print("[static http server] Recv_client_content:" + recv_client_content)
request_list = recv_client_content.split(" ")
request_method = request_list[0]
request_path = request_list[1]
#log("Request_path: -" + request_path+"-")
print("[static http server] Request_path: -" + request_path+"-")
if request_path == "/":
request_path = "/index.html"
with open(config.httpapidir + request_path, "rb") as file:
file_data = file.read()
response_data = sponse(file_data)
new_socket.send(response_data)
elif request_path == "/news":
request_path = "/news.html"
with open(config.httpapidir + request_path, "rb") as file:
file_data = file.read()
response_data = sponse(file_data)
new_socket.send(response_data)
elif request_path == "/list":
response_data = ''
for i in os.listdir(path=config.httpapidir+"/public/"):
response_data += """<p><a href="/"""+str(i)+'">'+i+'</a></p>\n'
new_socket.send(sponse(response_data.encode("utf-8")))
else:
try:
with open(config.httpapidir+"/public/" + request_path, "rb") as file:
file_data = file.read()
except Exception as e:
with open(config.httpapidir + "/error.html", "rb") as file:
file_data = file.read()
response_body = file_data
response_data = sponse(file_data)
new_socket.send(response_data)
new_socket.close()
def main():
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
tcp_server_socket.bind(("", config.port))
tcp_server_socket.listen(128)
while True:
new_socket, ip_port = tcp_server_socket.accept()
log("Ip_port: " + str(ip_port))
print("[static http server] Ip_port:" + str(ip_port))
sub_thread = threading.Thread(target=handle_client_request, args=(new_socket,))
sub_thread.setDaemon(True)
sub_thread.start()
if __name__ == '__main__':
main()
index.html
<p>Index</p>
<p>File list<a> href="/list"</a></p>
<p>Server news<a> href="/news"</a></p>
error.html
<p>file not find.</p>
news.html
随意
run:
python httpserver.py
注意它每天会生成一个server_<time>.log在data里,记录一些信息。