def CheckAndSendAllOrderData(): global __lastSendTime, _server if (_server.client == None): return curTime = time.time() if (curTime - __lastSendTime) < globalsetting.globaldefine.DEF_SEND_ALL_INTERVAL: return __lastSendTime = time.time() sendInfo = process.orderdata.GetAllFirstOneDesInfo() if sendInfo == '{}': return GetLogger().debug('发送所有订单数据,len:%d' % len(sendInfo)) buffSend = '' nDataLen = len(sendInfo) buffSend = common.commfunc.WriteWORD(buffSend, nDataLen) buffSend = common.commfunc.WriteString(buffSend, nDataLen, sendInfo) buffSend = _server.client.packParse.PackData( buffSend, globaldefine.RECGS_PROCESS_ORDER_ID_REQ) _server.client.Send(buffSend) GetLogger().debug('send to gameserver:%s' % buffSend)
def Init(): try: #查看所有有充值到但是没有被gs处理过的 strSql="select * from %s where IsProcess=0 and DateExchange is not NULL order by DateExchange"%globalsetting.globalinfo.DB_EXCHANGE_TABLE_NAME result=dblogic.logicprocess.GetDBObj().RunSql( strSql ) for feedbackInfo in result: #遍历,并且插入 if not __dicOrder.has_key( feedbackInfo['PlayerID'] ): data=PlayerData() data.nPlayerID=feedbackInfo['PlayerID'] __dicOrder[ feedbackInfo['PlayerID'] ]=data __dicOrder[ feedbackInfo['PlayerID'] ].listOrderInfo.append( (str(feedbackInfo['OrderID']), feedbackInfo['Amount']) ) try: GetLogger().info( "读取到玩家:%d 未处理的订单数据是:%s"%( data.nPlayerID, str( feedbackInfo['OrderID'] ) ) ) except: GetLogger().error( "获得的反馈数据是:%s"%str(feedbackInfo) ) GetLogger().error( traceback.format_exc() ) return True except: GetLogger().error( traceback.format_exc() ) return False
def _OnRecv_0097(self, lpData): pos = 0 nLen, pos = common.commfunc.ReadWORD(lpData, pos) strInfo, pos = common.commfunc.ReadString(lpData, pos, nLen) GetLogger().info('订单处理GS返回的内容是:%s' % (strInfo)) try: dictParam = eval(strInfo) except: GetLogger().error(traceback.format_exc()) GetLogger().error('接收到订单处理结果的信息是:%s' % (strInfo)) return if (dictParam["ResultCode"] == globaldefine.PROCESS_EXCHANGE_SUCCESS or dictParam["ResultCode"] == globaldefine.PROCESS_EXCHANGE_ORDER_ID_REPEAT): dblogic.logicprocess.SetExchangeProcessed( dictParam["OrderID"], dictParam["ResultCode"] == globaldefine.PROCESS_EXCHANGE_ORDER_ID_REPEAT) process.orderdata.DelData(dictParam["PlayerID"], dictParam["OrderID"]) return GetLogger().error('订单处理错误,GS返回的内容是:%s' % (strInfo))
def UnInitAll(): print 'program begin exit' GetLogger().info('全局开始逆初始化') GetLogger().info('逆初始化步骤0') process.orderdata.UnInit() GetLogger().info('逆初始化步骤1') process.httpcoreprocess.Stop() GetLogger().info('全局逆初始化完毕')
def OnRecvPacket(self, lpData, nhead): GetLogger().debug('recv data:%s' % (common.commfunc.BinToStr(lpData))) strFuncName = "_OnRecv_%04d" % (nhead) if hasattr(self, strFuncName): try: GetLogger().info("%s, PackLen=%d" % (strFuncName, len(lpData))) getattr(self, strFuncName)(lpData) except: GetLogger().error("%s fail! %s" % (strFuncName, traceback.format_exc())) return GetLogger().warning("未定义封包的处理函数:%s" % (strFuncName))
def Main(): try: InitAll() if process.httpcoreprocess.Start(): thread.start_new(Input, ()) Run() else: GetLogger().critical('begin httpserver error!') except: GetLogger().info('exception:' + traceback.format_exc()) print traceback.format_exc()
def InitAll(): print 'program begin init' GetLogger().info('program begin init') if process.orderdata.Init(): GetLogger().info('process.orderdata初始化成功!') else: GetLogger().error('process.orderdata初始化失败!') raise 'feedback db init failed' print 'init success'
def handle_accept(self): #接受client socket的連線 sock, address = self.accept() GetLogger().info('New client from : ' + str(address)) if (self.client): GetLogger().info('already connect address:%s refuse connect' % (str(self.client.addr))) sock.close() return #自定义的客户端类 self.client = Client(sock)
def SetExchangeProcessed(strOrderID, bRepeat): strSql = "update %s set DateProcess=now(), IsProcess=1 where OrderID='%s' and IsProcess=0" % ( globalinfo.DB_EXCHANGE_TABLE_NAME, strOrderID) if __dbObj.ExecSql(strSql) > 0: GetLogger().info('SetExchangeProcessed succees!') return True else: if not bRepeat: GetLogger().error('SetExchangeProcessed保存数据失败,执行SQL语句:%s' % strSql) else: GetLogger().warning( 'SetExchangeProcessed保存数据失败,可能是重复设置数据,执行SQL语句:%s' % strSql) return False
def GetDataByOrderID(strOrderID): strSql = "select * from %s where OrderID='%s'" % ( globalinfo.DB_EXCHANGE_TABLE_NAME, strOrderID) retList = __dbObj.RunSql(strSql) if not retList: GetLogger().error('根据订单号获得数据失败,sql:%s 结果:%s' % (strSql, str(retList))) return False if len(retList) > 0: return retList else: GetLogger().error('根据订单号获得数据失败,sql:%s' % strSql) return False
def run(self): global _srv try: _srv.serve_forever() except: GetLogger().critical( traceback.format_exc() ) raise
def do_GET(self): #不处理浏览器的logo请求 if( self.path=='/favicon.ico' ): return dicParam=commfunc.GetHttpParam( self.path ) if dicParam=='': self.wfile.write( GetErrorStr(DEF_PARAM_ERROR) ) return try: strServerName=str.split( dicParam['trade_no'], '_' )[0] strServerPath=config.ServerList[strServerName][0] nPort=config.ServerList[strServerName][1] conn=httplib.HTTPConnection( strServerPath, nPort ) conn.request('GET', self.path) strRet=conn.getresponse().read() self.wfile.write( strRet ) except: GetLogger().warning( '发生了错误:%s path:%s'%( traceback.format_exc(), self.path ) ) self.wfile.write( ("{'status':'error_12'}").replace( '\'' , '"') ) self.close_connection();
def GetAllFirstOneDesInfo(): commfunc.ScopeLock(__lock) try: dicRet={} for key,value in __dicOrder.items(): if len( value.listOrderInfo )==0: GetLogger().warning( '无法得到玩家:%s 的任何充值信息描述'%str(key) ) continue allOrderData=value.listOrderInfo[0] dicRet[ '%s'%key ]={ 'OrderID':'%s'%allOrderData[0], 'Amount':int(allOrderData[1]) } except: GetLogger().error( traceback.format_exc() ) return str( dicRet ).replace('\'', '"')
def _OnRecv_0094(self, lpData): pos = 0 nLen, pos = common.commfunc.ReadWORD(lpData, pos) GetLogger().debug('pos=%d nLen=%d Data:%s' % (pos, nLen, common.commfunc.BinToStr(lpData[pos:]))) strInfo, pos = common.commfunc.ReadString(lpData, pos, nLen) GetLogger().debug('接收到请求GUID的信息是:%s' % strInfo) try: dictParam = eval(strInfo) except: GetLogger().error(traceback.format_exc()) GetLogger().error('接收到请求GUID的信息是:%s' % (strInfo)) return strGuid = str(uuid.uuid1()) strGuid = globalsetting.config.GetMainConfig().get( 'platform', 'ServerName') + '_' + strGuid dictResult = {} dictResult['OrderID'] = strGuid if dblogic.logicprocess.CreateOrderInfo(strGuid, dictParam['PlayerID'], dictParam['PlayerLevel'], dictParam['ZoneID'], int(dictParam['UserID'])): #成功返回结果给gs dictResult['Result'] = 1 else: #返回失败的信息给gs dictResult['Result'] = 0 dictResult['PlayerID'] = dictParam['PlayerID'] strResult = str(dictResult) strResult = strResult.replace('\'', '"') buffSend = '' nDataLen = len(strResult) buffSend = common.commfunc.WriteWORD(buffSend, nDataLen) buffSend = common.commfunc.WriteString(buffSend, nDataLen, strResult) buffSend = self.__client.packParse.PackData( buffSend, globaldefine.RECGS_GEN_GUID_ACK) GetLogger().info('创建订单,返回数据:%s' % buffSend) self.__client.sendBuffer += buffSend
def __DelData( nPlayerID, strOrderID ): if not __dicOrder.has_key( nPlayerID ): GetLogger().warning( 'DelData无法获得数据通过PlayerID:'+str(nPlayerID) ) return None GetLogger().debug( '删除已处理订单前的数据长度:%d'%len( __dicOrder[nPlayerID].listOrderInfo ) ) __dicOrder[nPlayerID].DelOrderInfo( strOrderID ) GetLogger().debug( '删除已处理订单后的数据长度:%d'%len( __dicOrder[nPlayerID].listOrderInfo) ) if len( __dicOrder[nPlayerID].listOrderInfo )>0: return True else: __dicOrder.pop( nPlayerID ) GetLogger().debug( '删除玩家充值反馈成功, nPlayerID:%d'%nPlayerID ) return True
def handle_close(self): self.close() self.sendBuffer = '' self.packParse.Clear() GetLogger().error('disconnect from gs,' + 'Addr:' + str(self.addr)) global _server _server.DelClient()
def DelData( nPlayerID, strOrderID ): commfunc.ScopeLock(__lock) try: ret=False ret=__DelData( nPlayerID, strOrderID ) except: GetLogger().error( traceback.format_exc() ) return ret
def GetDataByPlayerID( nPlayerID ): commfunc.ScopeLock(__lock) try: ret=None ret=__GetDataByPlayerID( nPlayerID ) except: GetLogger().error( traceback.format_exc() ) return ret
def Begin(): global _srv #日志初始化 logPath = os.getcwd() + "/log"; if not os.path.exists(logPath): os.mkdir(logPath) log.InitLog(logPath, "exchange", config.PrintLog, config.Debug) GetLogger().info( 'Server start...' ) #服务器启动 _srv.serve_forever()
def RunSql(self, strSql): commfunc.ScopeLock(self.__dbLock) #self.__CheckAndReconnect() cursor = self.__con.cursor((MySQLdb.cursors.DictCursor)) try: cursor.execute(strSql) except MySQLdb.OperationalError, error: GetLogger().error('exec sql:%s failed:%s' % (strSql, str(error))) self.__ConnectDB() cursor.execute(strSql)
def AddData( nPlayerID, strOrderID, nAmount, dbObj ): commfunc.ScopeLock(__lock) try: ret=False ret=__AddData(nPlayerID, strOrderID, nAmount, dbObj) except: GetLogger().error( traceback.format_exc() ) return ret
def ExecSql(self, strSql): common.commfunc.ScopeLock(self.__dbLock) #self.__CheckAndReconnect() cursor = self.__con.cursor() try: cursor.execute(strSql) ret = cursor.rowcount except MySQLdb.OperationalError, error: GetLogger().error('exec sql:%s failed:%s' % (strSql, str(error))) self.__ConnectDB() cursor.execute(strSql)
def __ConnectDB(self): try: cfg = config.GetMainConfig() strUser = cfg.get('db', 'User', True) strPsw = cfg.get('db', 'Psw', True) strHost = cfg.get('db', 'Host', True) nPort = string.atoi(cfg.get('db', 'Port', True), 10) strDBName = cfg.get('db', 'Name', True) GetLogger().info('connect db Host:%s,port:%d' % (strHost, nPort)) self.__con = MySQLdb.connect(host=strHost, user=strUser, passwd=strPsw, db=strDBName, charset="utf8", port=nPort) return True except: GetLogger().error('connect db failed, error:' + traceback.format_exc()) raise
def Process(): try: #数据发送和接收 asyncore.loop(globalsetting.globaldefine.DEF_SELECT_INTERVAL_TIME, False, None, 1) # if not IsConnected(): # Connect() # else: # CheckAndSendHeartMsg() except: GetLogger().error(traceback.format_exc())
def do_GET(self): #不处理浏览器的logo请求 if( self.path=='/favicon.ico' ): return dicParam=commfunc.GetHttpParam( self.path ) GetLogger().info( 'http recv client addr:%s path:%s '%( self.client_address, self.path ) ) if dicParam=='': self.wfile.write( ("{'status':'error_11'}").replace( '\'' , '"') ) return try: #进入处理流程 strRet=exchange.Process( dicParam ) except: GetLogger().error( 'http recv client traceback:%s'%( traceback.format_exc() ) ) #json数据字符串是用双引号"而不是单引号' strRet=strRet.replace( '\'' , '"') GetLogger().info( '返回:%s'%( strRet ) ) self.wfile.write( strRet )
def CheckAndSendHeartMsg(): global __lastSendTime, _server if (_server.client == None): return if time.clock( ) - _server.client.lastSendHeartClock > globaldefine.DEF_HEART_INTERVAL: buffSend = '' buffSend = common.commfunc.WriteBYTE(buffSend, 0) buffSend = _server.client.packParse.PackData( buffSend, globaldefine.RECGS_HEART_REQ) _server.client.Send(buffSend) GetLogger().debug('发送心跳') _server.client.lastSendHeartClock = time.clock()
#只返回数量 def ExecSql(self, strSql): common.commfunc.ScopeLock(self.__dbLock) #self.__CheckAndReconnect() cursor = self.__con.cursor() try: cursor.execute(strSql) ret = cursor.rowcount except MySQLdb.OperationalError, error: GetLogger().error('exec sql:%s failed:%s' % (strSql, str(error))) self.__ConnectDB() cursor.execute(strSql) except: GetLogger().error('exec sql failed:' + strSql + traceback.format_exc()) cursor.close() raise cursor.close() self.__con.commit() return ret #查询语句,返回查询到的内容 def RunSql(self, strSql): commfunc.ScopeLock(self.__dbLock) #self.__CheckAndReconnect() cursor = self.__con.cursor((MySQLdb.cursors.DictCursor)) try: cursor.execute(strSql)
def handle_error(self): GetLogger().error('client error')
def OnRecvPacket(self, curPack, head, client): try: self.packDispatcher.OnRecvPacket(curPack, head) except: GetLogger().error('收到封包失败:%s' % traceback.format_exc())
def handle_write(self): sent = self.send(self.sendBuffer) self.sendBuffer = self.sendBuffer[sent:] GetLogger().debug('发送了数据,长度:%s' % sent)