python socket实现web 服务端

实现一个简易的web服务端

 

 

#!/usr/bin/python
# -*- coding: utf-8 -*-
#Author:xianyanghua
# @Time    :2019/7/25 14:17
# @File    : test.py
# @Software: PyCharm
import socket
class view(object):
    def __init__(self,con,url):
        self.con=con
        self.url=url
    def sendHtml(self):
        self.con.send("HTTP/1.1 201 OK\r\n\r\n".encode('utf-8'))
        self.con.send('

hello

'.encode('utf-8')) def sendLogin(self): self.con.send("HTTP/1.1 201 OK\r\n\r\n".encode('utf-8')) self.con.send('

login

'.encode('utf-8')) def chargeUrl(self): for i, v in url_route.items(): print(url_route[i]) if i == self.url: if hasattr(view1, url_route[i]): print('.............') getattr(view1, url_route[i])() socket=socket.socket() url_route={ '/index': 'sendHtml', '/login': 'sendLogin' } socket.bind(('127.0.0.1',8003)) socket.listen(5) while True: con,addr=socket.accept() print(con,addr) while True: try: content = con.recv(1024).decode('utf-8') content = content.split('\r\n')[0] url = content.split()[1] view1 = view(con,url) print(url) view1.chargeUrl() # f=open('request.txt','w') # f.write(recv_data) # f.close()] con.close() break import time time.sleep(10) except Exception as e: print(e) socket.close() ##路由模块呢 # GET /favicon.ico HTTP/1.1 # Host: localhost:8003 # Connection: keep-alive # User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36 # Accept: image/webp,image/apng,image/*,*/*;q=0.8 # Referer: http://localhost:8003/ # Accept-Encoding: gzip, deflate, br # Accept-Language: zh-CN,zh;q=0.9 # Cookie: csrftoken=UPvd4hEAiws0FycrIC7427cSKjqPMJsXEwqVf6MNTASZYgfIOtmdunOcfunngRGQ

 

你可能感兴趣的:(python基础)