python--DenyHttp项目(2)--ACM监考服务器端

服务器端:

 

#coding:utf-8
'''
ServerGui.py
设置比赛开始时间
设置比赛结束时间
若时间无误启动监听服务
'''
import time
import re
import tkinter as tk
from tkinter import simpledialog
from DenyServer import *
import threading

class ServerGui():
    
    def __init__(self):
        '''开始时间,结束时间'''
        self.getEndTime = ''
        self.getStartTime = ''
        '''定义窗口布局'''
        self.root = tk.Tk()
        self.serverMark = 1
        self.root.title('404监考服务器')
        self.curWidth = 450
        self.curHeight = 85
        scnWidth,scnHeight = self.root.maxsize() 
        tmpcnf = '%dx%d+%d+%d'%(self.curWidth,self.curHeight,
                                (scnWidth-self.curWidth)/2,(scnHeight-self.curHeight)/2)
        self.root.geometry(tmpcnf)
        self.root.resizable(False, False)
        '''比赛开始时间Button'''
        self.setStartTimeButton = tk.Button(self.root,
                                       text='设置比赛开始时间:',
                                        height=1,width=15,padx=8,pady=1,
                                        font=("Arial",14),
                                        command=self.setStartTime)
        self.startTimeLable = tk.Label(self.root,text='00:00:00',font=("Arial",20))
        self.setStartTimeButton.grid(row=0,column=0,stick=tk.E)
        self.startTimeLable.grid(row=0,column=1,stick=tk.W)
        '''比赛结束时间Button'''
        self.setTimeButton = tk.Button(self.root,
                                       text='设置比赛结束时间:',
                                        height=1,width=15,padx=8,pady=1,
                                        font=("Arial",14),
                                        command=self.setEndTime)
        self.timeLable = tk.Label(self.root,text='00:00:00',font=("Arial",20))
        self.setTimeButton.grid(row=1,column=0,stick=tk.E)
        self.timeLable.grid(row=1,column=1,stick=tk.W)
        
        '''启动服务器'''
        if self.serverMark:
            self.threadStartServerServices = threading.Thread(target=self.checkTimeAndLocaltion)
            self.threadStartServerServices.start()

        self.root.mainloop()   
    '''检查时间是否设置'''
    def checkTimeAndLocaltion(self):
        while True:
            if self.getEndTime != '' and self.getStartTime != '':
                self.serverStart()
                break
            time.sleep(1)
    '''设置比赛开始时间'''
    def setStartTime(self):
        ch = simpledialog.askstring("比赛开始时间:", "时间格式例如:2017-07-12 00:00:15")
        pattern=re.compile(r'(\d{4}-\d{2}-\d{2})((\s\d{2}:\d{2}:\d{2}|))')
        try:
            s = pattern.search(ch).group()
            self.getStartTime = s
            self.startTimeLable.configure(text=s)
        except AttributeError:
            tk.messagebox.showerror('警告', "格式错误")
            self.setStartTime() 
        except TypeError:
            pass
    '''设置比赛结束时间'''
    def setEndTime(self):
        ch = simpledialog.askstring("比赛结束时间:", "时间格式例如:2017-07-12 00:00:15")
        pattern=re.compile(r'(\d{4}-\d{2}-\d{2})((\s\d{2}:\d{2}:\d{2}|))')
        try:
            s = pattern.search(ch).group()
            self.getEndTime = s
            self.timeLable.configure(text=s)
        except AttributeError:
            tk.messagebox.showerror('警告', "格式错误")
            self.setEndTime() 
        except TypeError:
            pass
    '''启动服务器端'''
    def serverStart(self):
        self.serverMark = 0
        '''模块接口'''
        server = ThreadTCPServer(initServerIp(), TCPHandler)
        TCPHandler.startTime = datetime.datetime.strptime(self.getStartTime, "%Y-%m-%d %H:%M:%S")
        TCPHandler.endTime   = datetime.datetime.strptime(self.getEndTime,   "%Y-%m-%d %H:%M:%S")

        server_thread = threading.Thread(target=server.serve_forever())
        server_thread.daemon = True
        server_thread.start()
        server_thread.join()
        server.shutdown()

if __name__ == '__main__':
    servergui = ServerGui()
#coding:utf-8
'''
DenyServer.py
使用socketserver创建一个服务器端(用前辈的模块,不如自己写的灵活,导致很多功能在接口处卡死)
'''
from socket import *
import threading
import socketserver
import datetime
import logging
from DenyItem.ServerGui import *

class TCPHandler(socketserver.BaseRequestHandler):
    
    '''处理request请求'''
    def handle(self):  
        
        self.BUFSIZE = 1024
        self.version = '1'
        self.clientIP = []
        '''获取request数据并删除头尾空格'''
        self.data = self.request.recv(self.BUFSIZE).strip().decode('utf-8')
        self.senddata = ''
        '''配置日志格式'''
        logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s :%(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='Serverlog.log',
                filemode='a')
        '''记录日志'''
        logging.info("{} send:" .format(self.client_address[0]) + str(self.data))
        '''响应客户端请求'''
        if self.data[0] == 'B':
            self.beginTime = self.data[2:]
            self.beginTime = datetime.datetime.strptime(self.beginTime,'%Y-%m-%d %H:%M:%S')
            if self.endTime == '' : 
                self.senddata = '0'
            elif self.startTime <= self.beginTime:
                self.senddata = '-2'
            elif self.beginTime >= self.endTime:
                self.senddata = '-1'
            else:
                self.senddata = self.endTime
        elif self.data[0] == 'E':
            '''报警模块'''
            '''BUG,获取IP'''
            
            if self.data[-3] == '.':
                self.id = int(self.data[-2:])
                logging.error('502 IP:' + str(self.id) + '号,正在作弊!!!')
            else:
                self.id = int(self.data[-3:]) - 110
                logging.error('404:' + str(self.id) + '号,正在作弊!!!')
        elif self.data[0] == 'V':
            if self.data[-1:] == self.version:
                self.senddata = '1'
            else:
                self.senddata = '-1'
        elif self.data[:2] == 'IP':
            '''更新上线列表'''
            if self.data[-3] == '.':
                '''502IP未定'''
                '''502IP未定'''
                '''502IP未定'''
                logging.info('502 上线:' + self.data[-2:])
            else:
                logging.info('404 上线:' + str(int(self.data[-3:])-110))
                
        self.request.sendall(str(self.senddata).encode('utf-8'))
        
    
class ThreadTCPServer(socketserver.ThreadingMixIn,socketserver.TCPServer):
    pass

def initServerIp():
    ADDR = HOST, PORT = gethostbyname(gethostname()), 1122
    return ADDR

if __name__=='__main__':
    
    server = ThreadTCPServer(initServerIp(), TCPHandler)
    TCPHandler.endTime = datetime.datetime.strptime('2017-7-27 20:00:00', "%Y-%m-%d %H:%M:%S")
    server_thread = threading.Thread(target=server.serve_forever())
    server_thread.daemon = True
    server_thread.start()
    server_thread.join()
    server.shutdown()
    
    
    

 

posted @ 2017-07-28 09:42  朤尧  阅读(411)  评论(0编辑  收藏  举报