def working(self): '''维护服务器的主逻辑代码''' try: self.debug("wait for connection...") pack = self.server_sock.accept() # 接受客户端的连接 _clientsock, _addr = pack # 解包 # 以下代码用于验证客户端是否是有效的客户端 _random_string = make_number_sequence() _clientsock.send( encryption(_random_string.encode(LMServer.ENCODING))) _message = _clientsock.recv(LMServer.BUFSIZE) data = decryption(_message) if data: data = data.decode(LMServer.ENCODING) if data == md5(_random_string, LMServer.ENCODING): self.debug("a connection from %s is built" % str(pack[1])) worker = LMClient(pack, self, debug=True) # 创建工作者 worker.start() worker.send_message(payback(MsgType.RESULT, msg=SUCCESS)) else: _clientsock.close() else: _clientsock.close() # 以上代码用于验证客户端是否是有效的客户端 # 遇到无效的客户端时直接关闭 except Exception as e: self.logger.log("unknow error happened at server main loop:%s" % str(e), LogType.ERROR, position="LMServer.working()")
def working2(self): ''' send message to server ''' while 1: if self.flag: self.flag = False msg = input("client@server") self.localsock.send(encryption(msg.encode(ENCODING))) print("消息已经发送了")
def connect(self): try: self.localsock.connect(self.server_addr) pwd = decryption(self.localsock.recv(BUFSIZE)).decode(ENCODING) pwd = encryption(md5(pwd,ENCODING).encode(ENCODING)) self.localsock.send(pwd) return True except Exception as e: print(e) return False
def send_message(self, info): '''发送一条消息,该条消息使用服务器加密规则进行加密和解密''' try: self.clientsock.send(encryption(info.encode(LMServer.ENCODING))) except ConnectionResetError as e: self.shutdown() except Exception as e: self.debug("LMotorClient.send_message:" + str(e)) self.server.logger.log( "unknown error happened when send message to client:%s" % str(e), LogType.ERROR, "LMClient.send_message()") self.shutdown()
def send_message(self, info): '''给管理员发送一条消息''' try: self.managersock.send(encryption(info.encode(LMServer.ENCODING))) except ConnectionResetError as e: self.clearsock(reason="在发送消息的时候遇到了connection_reset_error") except Exception as e: self.debug("LMotorManager.send_message:" + str(e)) self.server.logger.log( "unknown error happened when send a message to manager:%s" % str(e), LogType.ERROR, "LMMangaer.send_message()") self.clearsock(reason="在发送消息的时候遇到了未知的错误:{}".format(str(e)))
def working(self): ''' show message from server ''' while 1: try: msg = self.localsock.recv(BUFSIZE) msg = decryption(msg).decode(ENCODING) _obj = eval(msg) if _obj.get("type") == 999: msg = str({"type":999}) self.localsock.send(encryption(msg.encode(ENCODING))) else: print(_obj) self.flag = True except Exception as e: self.show_message(e) break