用python编写一个简单的httpserver

import socket
from multiprocessing import Process

class CHttpServer(object):
def __init__(self):
self.m_serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.m_serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.bind(8080)

def start(self):
self.m_serverSocket.listen(128)
while (True):
m_clientSocket, m_clientAddr = self.m_serverSocket.accept()
print('[%s,%s]用户连接上了服务器' % m_clientAddr)
handle_client_process = Process(target=self.handle_client, args=(m_clientSocket,))
handle_client_process.start()
m_clientSocket.close()

def handle_client(self, clientSocket):
request_data = clientSocket.recv(1024)
print('接收到的数据:%s' % request_data.decode())

response = ''
response_start_line = "HTTP/1.2 200 OK\r\n"
response_headers = "Server: My server\r\nName: hello world\r\nProvince: Shanxi\r\n"
# response_start_line = ""
# response_headers = ""
file_data = r'非法操作'
response_body = file_data
response = response_start_line + response_headers + "\r\n" + response_body
print('发送的数据[%s]' % response)
clientSocket.send(bytes(response, "gbk"))

def bind(self, port):
self.m_serverSocket.bind(('127.0.0.1', port))

if __name__ == '__main__':
server = CHttpServer()
server.start()

浏览器打开 127.0.0.1:8080

 

 终端输出如下

[127.0.0.1,59393]用户连接上了服务器
[127.0.0.1,59394]用户连接上了服务器
接收到的数据:GET / HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
Cache-Control: max-age=0
sec-ch-ua: "Chromium";v="110", "Not A(Brand";v="24", "Microsoft Edge";v="110"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.57
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6


发送的数据[HTTP/1.2 200 OK
Server: My server
Name: hello world
Province: Shanxi

非法操作]

 

posted @ 2023-02-28 23:35  腹肌猿  阅读(495)  评论(0编辑  收藏  举报