【原创源码】【python语言】+http服务器实现
主要实现了模拟注册和登录功能,只用文件存储。大家也可以修改成数据库1、脚本启动代码from ChttpServer import CHttpServer
def main():
http_server = CHttpServer.CHttpServer()
http_server.bind(8000)
http_server.start()
if __name__ == "__main__":
main()
2.http服务器实现类
import socket
import sys
import re
from multiprocessing import Process
class CHttpServer(object):
"""Httpserver服务端类"""
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)
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)
request_lines=request_data.splitlines()
#print(len(request_lines))
strlist=[]
for line in request_lines:
strlist=str(line).split('&')
if len(strlist) > 1:
break
#print(strlist)
userinfolist = strlist
user_info='&'.join(userinfolist)
#print(userinfolist)
#用户名&密码&操作类型&来源
#解析请求报文
'''
报文协议格式:clientparam=&username&pwd&method&type&.
type:0 注册 1登录
'''
file_data=''
response_body=''
response=''
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n"
if strlist=='1':#注册
"""写注册文件"""
fp = open('userinfo.txt','a+')
fp.write(user_info)
fp.write('\n')
fp.close()
file_data=r'<b>恭喜您,注册成功:'+ (strlist+'</b>')
response_body = file_data
response = response_start_line + response_headers + "\r\n" + response_body
elif strlist=='2': #登录
"""登录系统"""
fp = open('userinfo.txt','r')
for line in fp.readlines():
if line.replace('\n','') == user_info.replace('\n',''):
#print(user_info)
file_data=r'<b>恭喜您,登录成功:'+ (strlist+'</b>')
response_body = file_data
response = response_start_line + response_headers + "\r\n" + response_body
break
# 向客户端返回 响应数据
fp.close()
elif strlist=='3': #重置密码
pass
else:
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 start_response(self,status,headers):
response_headers = "HTTP/1.1 " + status + "\r\n"
for header in headers:
response_headers += "%s: %s\r\n" % header
self.response_headers = response_headers
#绑定端口
def bind(self,port):
self.m_serverSocket.bind(('',port))
def parseline(self,strcon):
"""解析字符串"""
pass 用flask不香难道不香吗 我也想说 flask 不香吗 ?
你好,requset_data=clientsocket.recv(1024)之后不解码吗?这里接受的是客户端发过来的套接字,还是二进制的。
open('userinfo.txt','r')建议访问模式改为‘rb'模式,这里是个坑
怎么没看到:aa=CHttpServer()
aa.start()
m_clientSocket.close()你这里怎么刚开始就关闭客户端,后面还能发送吗? 可以参考一下 一颗草zZ 发表于 2019-12-14 23:27
你好,requset_data=clientsocket.recv(1024)之后不解码吗?这里接受的是客户端发过来的套接字,还是二进制 ...
接受建议,start在上面,类单独一个py 一颗草zZ 发表于 2019-12-14 23:32
可以参考一下
确实更好些
页:
[1]