def askReceived(self, request): """远程调用请求到达时的处理\n """ _key = request['_key'] _name = request['_name'] _args = request['_args'] _kw = request['_kw'] method = self.getRemoteMethod(_name) try: result = self.callRemoteMethod(method, _args, _kw) except Exception as e: result = None log.err(_stuff=e, _why=traceback.format_exc()) error = str(e) else: error = None if _key: response = { '_msgtype': ANSWER_SIGNAL, '_key': _key, 'result': result, "error": error } _response = marshal.dumps(response) self.writeData(_response)
def unpack(self,dpack): '''解包 ''' try: ud = struct.unpack('!sssss3I',dpack) except struct.error,de: log.err(de,traceback.format_exc()) return {'result':False,'command':0,'length':0}
def doWhenStop(): """服务器关闭前的处理 """ for gamer in GamersManager()._gamers.values(): try: gamer.updateGamerDBInfo() GamersManager().dropGamer(gamer) except Exception as ex: log.err(ex)
def dropClient(self,sceneId,clientId): '''清除一个客户端''' sceneser=self.getSceneServerById(sceneId) if sceneser: try: sceneser.dropClient(clientId) except Exception: msg="sceneId:%d---------clientId:%d"%(sceneId,clientId) log.err(msg)
def callChildNotForResult(self,childId,*args,**kw): '''调用子节点的接口\n @param childId: int 子节点的id ''' child = self._childs.get(childId,None) if not child: log.err("child %s doesn't exists"%childId) return child.callbackChildNotForResult(*args,**kw)
def callChildByNameNotForResult(self,childname,*args,**kw): '''调用子节点的接口\n @param childId: int 子节点的id ''' child = self.getChildByName(childname) if not child: log.err("child %s doesn't exists"%childname) return child.callbackChildNotForResult(*args,**kw)
def callChildNotForResult(self, childId, *args, **kw): '''调用子节点的接口\n @param childId: int 子节点的id ''' child = self._childs.get(childId, None) if not child: log.err("child %s doesn't exists" % childId) return child.callbackChildNotForResult(*args, **kw)
def callChildByName(self, childname, *args, **kw): '''调用子节点的接口\n @param childname: str 子节点的名称 ''' child = self.getChildByName(childname) if not child: log.err("child %s doesn't exists" % childname) return return child.callbackChild(*args, **kw)
def callChildByNameNotForResult(self, childname, *args, **kw): '''调用子节点的接口\n @param childId: int 子节点的id ''' child = self.getChildByName(childname) if not child: log.err("child %s doesn't exists" % childname) return child.callbackChildNotForResult(*args, **kw)
def callChild(self,childname,*args,**kw): '''调用子节点的接口\n @param childname: str 子节点的名称 ''' child = self.getChild(childname) if not child: log.err("child %s doesn't exists"%childname) return return child.callbackChild(*args,**kw)
def callChildNotForResult(self,childname,*args,**kw): '''调用子节点的接口\n @param childname: str 子节点的名称 ''' child = self._childs.get(childname,None) if not child: log.err("child %s doesn't exists"%childname) return child.callbackChildNotForResult(*args,**kw)
def excuteSQL(tablename,sql): conn = dbpool.connection(write=True,tablename=tablename) cursor = conn.cursor() count = 0 try: count = cursor.execute(sql) conn.commit() except Exception,e: log.err(e,traceback.format_exc()) log.err(sql)
def pushObject(self,topicID , msg, sendList): """主动推送消息 """ for target in sendList: try: conn = self.getConnectionByID(target) if conn: conn.safeToWriteData(topicID,msg) except Exception,e: log.err(e,traceback.format_exc())
def excuteSQL(tablename, sql): conn = dbpool.connection(write=True, tablename=tablename) cursor = conn.cursor() count = 0 try: count = cursor.execute(sql) conn.commit() except Exception, e: log.err(e, traceback.format_exc()) log.err(sql)
def pushObject(self, topicID, msg, sendList): """主动推送消息 """ for target in sendList: try: conn = self.getConnectionByID(target) if conn: conn.safeToWriteData(topicID, msg) except Exception, e: log.err(str(e))
def _run(self): """执行协议 """ while True: # msg = self.sock.recv() try: pyobj = self.sock.recv_pyobj() tablename,sql = pyobj excuteSQL(tablename, sql) except Exception,e: log.err(_stuff=e,_why=traceback.format_exc())
def g(self, gid): '''根据id获取翻译信息''' try: info = self.info.get(gid) if not info: log.err(str(gid)) return str(gid) return info except: return str(gid) log.err("%s不存在" % gid)
def _run(self): """执行协议 """ while True: # msg = self.sock.recv() try: pyobj = self.sock.recv_pyobj() tablename, sql = pyobj excuteSQL(tablename, sql) except Exception, e: log.err(_stuff=e, _why=traceback.format_exc())
def g(self,gid): '''根据id获取翻译信息''' try: info=self.info.get(gid) if not info: log.err(str(gid)) return str(gid) return info except: return str(gid) log.err("%s不存在"%gid)
def _run(self): """执行协议 """ address = 'tcp://%s:%s'%self.to_db_address self.sock.connect(address) while True: try: message = self.inbox.get() self.sock.send_pyobj(message) except Exception as e: log.err(_stuff=e,_why=traceback.format_exc()) log.msg(str(message))
def _run(self): """执行协议 """ address = 'tcp://%s:%s' % self.to_db_address self.sock.connect(address) while True: try: message = self.inbox.get() self.sock.send_pyobj(message) except Exception as e: log.err(_stuff=e, _why=traceback.format_exc()) log.msg(str(message))
def UpdateWithDict(tablename,props,prere): """更新记录 """ sql = forEachUpdateProps(tablename, props, prere) conn = dbpool.connection(write=True,tablename=tablename) cursor = conn.cursor() count = 0 try: count = cursor.execute(sql) conn.commit() except Exception,e: log.err(e,traceback.format_exc()) log.err(sql)
def UpdateWithDict(tablename,props,prere): """更新记录 """ sql = forEachUpdateProps(tablename, props, prere) conn = dbpool.connection() cursor = conn.cursor() count = 0 try: count = cursor.execute(sql) conn.commit() except Exception,e: log.err(e) log.err(sql)
def InsertIntoDB(tablename,data): """写入数据库 """ sql = forEachPlusInsertProps(tablename,data) conn = dbpool.connection() cursor = conn.cursor() count = 0 try: count = cursor.execute(sql) conn.commit() except Exception,e: log.err(e) log.err(sql)
def DeleteFromDB(tablename,props): '''从数据库中删除 ''' prers = FormatCondition(props) sql = """DELETE FROM %s WHERE %s ;"""%(tablename,prers) conn = dbpool.connection(write=True,tablename=tablename) cursor = conn.cursor() count = 0 try: count = cursor.execute(sql) conn.commit() except Exception,e: log.err(e,traceback.format_exc()) log.err(sql)
def callTarget(self, targetKey, *args, **kw): '''call Target @param conn: client connection @param targetKey: target ID @param data: client data ''' target = self.getTarget(targetKey) if not target: log.err('the command ' + str(targetKey) + ' not Found on service') return None if targetKey not in self.unDisplay: log.msg("call method %s on service[single]" % target.__name__) response = target(*args, **kw) return response
def callTarget(self,targetKey,*args,**kw): '''call Target by Single @param conn:client connection @param targetKey:target ID @param data:client data ''' target=self.getTarget(targetKey) if not target: log.err('the command' +str(targetKey)+'not Found on service') return None if targetKey not in self.unDisplay: log.msg("call method %s on service[single]"%target.__name__) response=target(targetKey,*args,**kw) return response
def NetConnLost_2(dynamicId): '''loginout ''' gamer=GamersManager().getGamerBydynamicId(dynamicId) if not gamer: return True try: gamer.updateGamerDBInfo() GamersManager().dropGamer(gamer) gamer.playerInner.dbupdate() except Exception as ex: log.err(ex) finally: return True
def updateGamerInfo(characterId,props): '''''' sqlstr=util.forEachUpdateProps('tb_character',props,{'id':characterId}) conn=dbpool.connection() cursor=conn.cursor() count=cursor.execute(sqlstr) conn.commit() cursor.close() conn.close() if count>=1: return True else: log.err(sqlstr) return False
def _run(self): """执行协议 """ self.connectionMade() try: while True: data = self.transport.recv(1024) if not data: break # gevent.spawn(self.dataReceived,data) self.dataReceived(data) except Exception,e: if not isinstance(e, socket.error): log.err(system = self.logPrefix()) self.connectionLost(reason=e)
def doDataReceived(self, message): if message is None: return try: message = CustProtc.decoder(message) if message['m'] > 1 and getattr(self, "pid", None): #用户登陆成功后其他消息全部转发到gate GlobalObject().wsapp.service.callTarget(200, self, message) elif message['m'] == 1 or message['m'] == 0: GlobalObject().wsapp.service.callTarget( message['m'], self, message) else: raise Exception("invalid message. data: %s" % message) except Exception, e: log.err(e) self.loseConnection()
def _run(self): """执行协议 """ self.connectionMade() try: while True: data = self.transport.recv(1024) if not data: break import gevent gevent.spawn(self.dataReceived,data) # self.dataReceived(data) except Exception,e: if not isinstance(e, socket.error): log.err(e,traceback.format_exc()) self.connectionLost(reason=e)
def askReceived(self,request): """远程调用请求到达时的处理\n """ _key = request['_key'] _name = request['_name'] _args = request['_args'] _kw = request['_kw'] method = self.getRemoteMethod(_name) try: result = self.callRemoteMethod(method, _args, _kw) except Exception as e: result = None log.err(_stuff=e,_why=traceback.format_exc()) error=str(e) else: error = None if _key: response = {'_msgtype':ANSWER_SIGNAL,'_key':_key,'result':result,"error":error} _response = marshal.dumps(response) self.writeData(_response)
def callTargetSingle(self, targetKey, *args, **kw): """call Target by Single @param conn: client connection @param targetKey: target ID @param data: client data """ self._lock.acquire() try: target = self.getTarget(targetKey) if not target: log.err('the command ' + str(targetKey) + ' not Found on service') return None defer_data = target(targetKey, *args, **kw) if not defer_data: return None d = defer.Deferred() d.callback(defer_data) finally: self._lock.release() return d
def getDropByid(leagueindex, category): '''根据Leagueindex获取掉落物品信息 @param leagueindex: int npc所在联盟 @param category:int 比赛类型 ''' data = {} if category == 7: data = TrainMatch_Dropout.get(leagueindex, None) elif category == 1: data = Challenge_Dropout.get(leagueindex, None) if not data: log.err(u'掉落表填写错误存在掉落信息-掉落主键:%d' % leagueindex) return None for item in data.get('itemid'): abss = random.randint(1, BASERATE) if abss >= 1 and abss <= item[2]: abss = random.randint(1, itemid[1]) item1 = Item(item[0]) item1.pack.setStack(abss) return item1 return None
def getDropByid(leagueindex,category): '''根据Leagueindex获取掉落物品信息 @param leagueindex: int npc所在联盟 @param category:int 比赛类型 ''' data={} if category==7: data=TrainMatch_Dropout.get(leagueindex,None) elif category==1: data=Challenge_Dropout.get(leagueindex,None) if not data: log.err(u'掉落表填写错误存在掉落信息-掉落主键:%d'%leagueindex) return None for item in data.get('itemid'): abss=random.randint(1,BASERATE) if abss>=1 and abss<=item[2]: abss=random.randint(1,itemid[1]) item1=Item(item[0]) item1.pack.setStack(abss) return item1 return None
def msg_2(_conn, data): """ NewPlayerMsg :param _conn: 链接对象 :param data: 客户端数据包 :return: """ uid = getattr(_conn, "uid", None) #分配房间 room_id = RoomManager().joinRandomRoom(_conn, 2) if room_id: setattr(_conn, 'room_id', room_id) room = RoomManager().getRoom(room_id) if room: player = room.getPlayer(uid) if player: player.setState(1) resp = Common_pb2.CommonResponse() resp.state = True # GlobalObject().netfactory.pushObject(2, resp, [_conn.transport.sessionno]) _conn.safeToWriteData(resp, 2) else: log.err("add room error!!!") return