def create_account(t, connection, loginserver, address): close = connection is None try: if connection is None: connection = mysql_connection.get_conn() userid = 0 while userid == 0: uid = random.randint(11000, 99999) if query_account_by_id(connection, uid) is None: userid = uid sql = config.get("sql", "sql_create_account") % ( userid, loginserver.account, StringUtils.phoneToNick(loginserver.nick), loginserver.sex, config.get("gateway", "head_url") % random.randint(1, 50), StringUtils.md5(loginserver.account), int(t), int(t), address, loginserver.device) with connection.cursor() as cursor: cursor.execute(sql) connection.commit() except: if close and connection is not None: connection.rollback() print traceback.print_exc() finally: if close and connection is not None: connection.close()
def login(self): code = StringUtils.randomNum(6) # self.redis.setex(self.account + "_code", int(code), 10) loginserver = ReqLoginServer() loginserver.account = self.account loginserver.nick = self.account loginserver.password = StringUtils.md5(self.account) loginserver.cls = WECHAT self.send_data(LOGIN_SVR, loginserver)
def start(): gl.set_v("serverlogger", LoggerUtils("niuniu")) gl.set_v("message-handle-queue", TestQueue()) gl.set_v("rebate-handle-queue", TestQueue()) gl.set_v("update_currency", TestQueue()) gl.set_v("game_details", TestQueue()) gl.set_v("play-handle", {}) uuid = StringUtils.randomStr(32) gl.set_v("uuid", uuid) gl.set_v("redis", RedisUtils()) gl.get_v("redis").startSubscribe([uuid], [message_handle]) gl.set_v("match_info", json.loads(config.get("niuniu", "match"))) threading.Thread(target=game_handle.handle, args=(game_handle(), gl.get_v("message-handle-queue"),), name='message-handle-queue').start() threading.Thread(target=rebate_handle.handle, args=(rebate_handle(), gl.get_v("rebate-handle-queue"),), name='rebate-handle-queue').start() threading.Thread(target=GameDetailsHandle.handle, args=(GameDetailsHandle(), gl.get_v("game_details"),), name='game_details').start() threading.Thread(target=UpdateCurrencyHandle.handle, args=(UpdateCurrencyHandle(), gl.get_v("update_currency"),), name='update_currency').start() Server.initCommand() Server.register()
def send(self, data): md5str = StringUtils.md5(self.newmd5keyBytes + data) md5bytes = md5str.decode("utf-8") datalen = struct.pack(">i", len(data) + len(md5bytes) + 4) self.s.sendall(datalen) self.write(md5bytes) self.s.sendall(data)
def execute(self): while True: length = self.readInt(self.s) md5bytes = self.readStringBytes(self.s) length -= len(md5bytes) + 4 result = self.readBytes(self.s, length) if length == len(result) and 0 != len(result): md5result = StringUtils.md5(self.newmd5keyBytes + result) if md5bytes.decode("utf-8") == md5result: data = NetMessage() data.ParseFromString(result) gl.get_v("serverlogger").logger.info('''收到%d''' % data.opcode) if data.opcode == CHECK_VERSION: self.checkVersion(data) self.login() elif data.opcode == LOGIN_SVR: recLoginServer = RecLoginServer() recLoginServer.ParseFromString(data.data) if recLoginServer.state == SUCCESS: gl.get_v("serverlogger").logger.info( "login success") else: gl.get_v("serverlogger").logger.info( "login fail:" + str(recLoginServer.state)) self.close() return elif data.opcode == UPDATE_USER_INFO: user_info = RecUserInfo() user_info.ParseFromString(data.data) if user_info.allocId != 0: gl.get_v("serverlogger").logger.info( "client close:allocId:" + str(user_info.allocId)) self.close() else: self.accountId = user_info.playerId self.intoRoom() elif data.opcode == APPLY_ENTER_MATCH: recApplyEnterMatch = RecApplyEnterMatch() recApplyEnterMatch.ParseFromString(data.data) if recApplyEnterMatch.state != recApplyEnterMatch.SUCCESS: gl.get_v("serverlogger").logger.info( "enter match fail") self.close() elif data.opcode == ASK_ACTION: gl.get_v("serverlogger").logger.info("start bet") baiRenRecAsk = BaiRenRecAsk() baiRenRecAsk.ParseFromString(data.data) if baiRenRecAsk.type == 2: self.betScore = BetScore(self) threading.Thread(target=BetScore.execute, args=(self.betScore, ), name='betScore').start() elif data.opcode == SETTLE_GAME: gl.get_v("serverlogger").logger.info("end bet") if self.betScore is not None: self.betScore.close() self.betScore = None
def checkVersion(self, data): recCheckversion = RecCheckVersion() recCheckversion.ParseFromString(data.data) keyIndex = random.randint(0, len(recCheckversion.keys) - 1) checkversion = ReqCheckVersion() checkversion.keyIndex = keyIndex self.send_data(CHECK_VERSION, checkversion) self.newmd5keyBytes = StringUtils.md5( self.oldmd5keyBytes.decode("utf-8") + "+" + recCheckversion.keys[keyIndex])
def start(): try: gl.set_v("serverlogger", LoggerUtils("robot")) gl.set_v("redis", RedisUtils()) accounts = [] for i in range(0, 20): accounts.append("138000" + StringUtils.randomNum(4)) for a in accounts: threading.Thread(target=Client.execute, args=(Client(a, 7), ), name='robot').start() except: print traceback.print_exc() os._exit(0)
def start(): gl.set_v("serverlogger", LoggerUtils("wuziqi")) gl.set_v("message-handle-queue", TestQueue()) gl.set_v("update_currency", TestQueue()) gl.set_v("game_details", TestQueue()) uuid = StringUtils.randomStr(32) gl.set_v("uuid", uuid) gl.set_v("redis", RedisUtils()) gl.get_v("redis").startSubscribe([uuid], [message_handle]) threading.Thread(target=game_handle.handle, args=(game_handle(), gl.get_v("message-handle-queue"),), name='message-handle-queue').start() threading.Thread(target=GameDetailsHandle.handle, args=(GameDetailsHandle(), gl.get_v("game_details"),), name='game_details').start() threading.Thread(target=UpdateCurrencyHandle.handle, args=(UpdateCurrencyHandle(), gl.get_v("update_currency"),), name='update_currency').start() Server.initCommand() Server.register()
def update_login_with_info(t, connection, loginserver, address, device): close = connection is None try: if connection is None: connection = mysql_connection.get_conn() sql = config.get("sql", "sql_update_login_with_info") % ( # StringUtils.phoneToNick(loginserver.nick), loginserver.sex, loginserver.headUrl, int(t), address, device, # loginserver.account) StringUtils.phoneToNick(loginserver.nick), loginserver.sex, int(t), address, device, loginserver.account) with connection.cursor() as cursor: cursor.execute(sql) connection.commit() except: if close and connection is not None: connection.rollback() print traceback.print_exc() finally: if close and connection is not None: connection.close()
def handle(self, queue): while not self.__close: try: messages = queue.getall(20, True, 20) for message in messages: if message.opcode == LOGIN_SVR: self.send_to_gateway(LOGIN_SVR, None) elif message.opcode == CREATE_GAME: reqCreateGame = ReqCreateGame() reqCreateGame.ParseFromString(message.data) find = False games = gl.get_v("games") random.shuffle(games) for g in games: if g.alloc_id == reqCreateGame.allocId and g.state == RUNNING: self.sendToGame( g.uuid, CREATE_GAME, reqCreateGame.SerializeToString()) find = True break if not find: recCreateGame = RecCreateGame() recCreateGame.state = 1 self.send_to_gateway(CREATE_GAME, recCreateGame) elif message.opcode == JOIN_GAME: reqJoinGame = ReqJoinGame() reqJoinGame.ParseFromString(message.data) find = False if self.__redis.exists( str(reqJoinGame.gameId) + "_gameId"): gameId = self.__redis.get( str(reqJoinGame.gameId) + "_gameId") games = gl.get_v("games") random.shuffle(games) for g in games: if g.alloc_id == gameId and g.state == RUNNING: self.sendToGame(g.uuid, message.opcode, message.data) find = True break if not find: recJoinGame = RecJoinGame() recJoinGame.state = 1 recJoinGame.gameId = reqJoinGame.gameId self.send_to_gateway(JOIN_GAME, recJoinGame) elif message.opcode == APPLY_ENTER_MATCH: reqApplyEnterMatch = ReqApplyEnterMatch() reqApplyEnterMatch.ParseFromString(message.data) find = False games = gl.get_v("games") random.shuffle(games) for g in games: if g.alloc_id == reqApplyEnterMatch.allocId and g.state == RUNNING: self.sendToGame( g.uuid, APPLY_ENTER_MATCH, reqApplyEnterMatch.SerializeToString()) find = True recApplyEnterMatch = RecApplyEnterMatch() recApplyEnterMatch.state = recApplyEnterMatch.SUCCESS self.send_to_gateway(APPLY_ENTER_MATCH, recApplyEnterMatch) break if not find: recApplyEnterMatch = RecApplyEnterMatch() recApplyEnterMatch.state = recApplyEnterMatch.FAILD self.send_to_gateway(APPLY_ENTER_MATCH, recApplyEnterMatch) elif message.opcode == UPDATE_MATCH_INFO: reqUpdateMatchInfo = ReqUpdateMatchInfo() reqUpdateMatchInfo.ParseFromString(message.data) recUpdateMatchInfo = RecUpdateMatchInfo() for info in reqUpdateMatchInfo.infos: infos = recUpdateMatchInfo.infos.add() infos.allocId = info.allocId infos.level = info.level infos.games = 1 infos.players = 5 infos.totalPlayers = 10 self.send_to_gateway(UPDATE_MATCH_INFO, recUpdateMatchInfo) elif message.opcode == BANK_INFO: reqBankInfo = ReqBankInfo() reqBankInfo.ParseFromString(message.data) account = data_account.query_account_by_id( None, self.__userId) recBankInfo = RecBankInfo() recBankInfo.card = int( account.bank_gold.quantize(Decimal('0'))) recBankInfo.gold = int( account.bank_gold.quantize(Decimal('0'))) recBankInfo.integral = int( account.bank_integral.quantize(Decimal('0'))) self.send_to_gateway(BANK_INFO, recBankInfo) elif message.opcode == BANK_DEPOSIT or message.opcode == BANK_GET: reqOperateBank = ReqOperateBank() reqOperateBank.ParseFromString(message.data) account = data_account.query_account_by_id( None, self.__userId) if message.opcode == BANK_DEPOSIT and int( account.gold.quantize( Decimal('0'))) < reqOperateBank.card: break if message.opcode == BANK_DEPOSIT and int( account.gold.quantize( Decimal('0'))) < reqOperateBank.gold: break if message.opcode == BANK_DEPOSIT and int( account.integral.quantize( Decimal('0'))) < reqOperateBank.integral: break if message.opcode == BANK_GET and int( account.bank_gold.quantize( Decimal('0'))) < reqOperateBank.card: break if message.opcode == BANK_GET and int( account.bank_gold.quantize( Decimal('0'))) < reqOperateBank.gold: break if message.opcode == BANK_GET and int( account.bank_integral.quantize( Decimal('0'))) < reqOperateBank.integral: break gold = -reqOperateBank.card if message.opcode == BANK_DEPOSIT else reqOperateBank.card integral = -reqOperateBank.integral if message.opcode == BANK_DEPOSIT else reqOperateBank.integral data_account.update_currency(None, gold, integral, -gold, -integral, self.__userId) data_gold.create_gold(2, self.__userId, self.__userId, gold) recOprateBank = RecOprateBank() self.send_to_gateway(message.opcode, recOprateBank) self.update_currency(self.__userId) if self.__redis.exists(str(self.__userId) + "_room"): roomNo = self.__redis.get( str(self.__userId) + "_room") gameId = self.__redis.get(str(roomNo) + "_gameId") games = gl.get_v("games") random.shuffle(games) for g in games: if g.alloc_id == gameId and g.state == RUNNING: self.sendToGame(g.uuid, GAME_UPDATE_CURRENCY, None) break elif message.opcode == UPDATE_RANK: reqGameRank = ReqGameRank() reqGameRank.ParseFromString(message.data) accounts = data_account.ranking_by_gold( None, reqGameRank.number) recGameRank = RecGameRank() i = 0 for a in accounts: i += 1 playerRankInfo = recGameRank.playerDatas.add() playerRankInfo.rankId = i playerRankInfo.playerId = a.id playerRankInfo.rankVal = int( a.gold.quantize(Decimal('0'))) playerRankInfo.nick = a.nick_name playerRankInfo.headUrl = a.head_url if a.introduce is not None: playerRankInfo.introduce = a.introduce playerRankInfo.consumeVip = a.level self.send_to_gateway(message.opcode, recGameRank) elif message.opcode == MATCH_RECORD_INFO: reqMatchRecordInfo = ReqMatchRecordInfo() reqMatchRecordInfo.ParseFromString(message.data) records = data_record.get_records( reqMatchRecordInfo.allocIds, self.__userId) self.send_to_gateway(message.opcode, records) elif message.opcode == UPDATE_INTRODUCE: reqUpdateIntroduce = ReqUpdateIntroduce() reqUpdateIntroduce.ParseFromString(message.data) account = data_account.update_introduce( None, self.__userId, reqUpdateIntroduce.content) if None is not account: self.update_user_info(account) elif (5 < message.opcode < 23) or (27 < message.opcode < 34) or ( 99 < message.opcode < 200 ) or message.opcode == 38 or message.opcode == 1005: if self.__redis.exists(str(self.__userId) + "_room"): roomNo = self.__redis.get( str(self.__userId) + "_room") gameId = self.__redis.get(str(roomNo) + "_gameId") games = gl.get_v("games") random.shuffle(games) for g in games: if g.alloc_id == gameId and g.state == RUNNING: self.sendToGame(g.uuid, message.opcode, message.data) break elif message.opcode == PERSONAL: s = StringUtils.randomStr(32) self.__redis.setex( str(self.__userId) + "personalcode", s, 10) reqPersonalCode = ReqPersonalCode() reqPersonalCode.ParseFromString(message.data) code = RecPersonalCode() code.code = s code.opcode = reqPersonalCode.opcode self.send_to_gateway(PERSONAL, code) else: gl.get_v("serverlogger").logger.info( "无效协议%d,用户id%d" % (message.opcode, self.__userId)) except Empty: print("%d messagehandle received timeout close" % self.__userId) self.close() self.__server_receive.remove(self.__userId) except: print traceback.print_exc()
def do(self, path): self.response_line = ErrorCode.NOT_FOUND self.response_body = "error" self.response_head['Content-Type'] = 'text/html' gl.get_v("serverlogger").logger.info("路径%s" % str(path)) if path == "/addgold": userId = self.request_data["userId"] gold = self.request_data["gold"] type = self.request_data["type"] pwd = self.request_data["pwd"] if pwd == StringUtils.md5(userId + gold + type): data_account.update_currency(None, int(gold), 0, 0, 0, int(userId)) data_gold.create_gold(int(type), int(userId), int(userId), int(gold)) self.update_currency(int(userId)) if self.__redis.exists(str(userId) + "_room"): roomNo = self.__redis.get(str(userId) + "_room") gameId = self.__redis.get(str(roomNo) + "_gameId") games = gl.get_v("games") random.shuffle(games) for g in games: if g.alloc_id == gameId and g.state == RUNNING: self.sendToGame(g.uuid, GAME_UPDATE_CURRENCY, None) break self.response_line = ErrorCode.OK self.response_body = "ok" elif path == "/enable": userId = self.request_data["userId"] enable = self.request_data["enable"] pwd = self.request_data["pwd"] if pwd == StringUtils.md5(userId + enable): if enable == "false": self.send_to_gateway(LOGIN_SVR, None, int(userId)) if self.__redis.exists(str(userId) + "_room"): online = ReqUpdatePlayerOnline() online.state = enable == "true" roomNo = self.__redis.get(str(userId) + "_room") gameId = self.__redis.get(str(roomNo) + "_gameId") games = gl.get_v("games") random.shuffle(games) for g in games: if g.alloc_id == gameId and g.state == RUNNING: self.sendToGame(g.uuid, CHANGE_ONLINE, online) break self.response_line = ErrorCode.OK self.response_body = "ok" elif path == "/notice": notice = urllib.unquote(self.request_data["notice"].encode('utf8')) pwd = self.request_data["pwd"] if pwd == StringUtils.md5(notice): recSystemNotice = RecSystemNotice() recSystemNotice.msg = notice self.send_to_gateway(SYSTEM_NOTICE, recSystemNotice, -1) self.response_line = ErrorCode.OK self.response_body = "ok" elif path == "/online": gameuser = self.__redis.keys("*_room") connectuser = TcpCount().get_connect( int(config.get("gateway", "port"))) self.response_line = ErrorCode.OK self.response_body = str(len(gameuser)) + "," + str(connectuser) elif path == "/connectinfo": self.response_line = ErrorCode.OK self.response_body = TcpCount().get_info( int(config.get("gateway", "port"))) elif path == "/cheat": file = self.request_data["file"] value = self.request_data["value"] out = open('./conf/' + file, 'w') out.write(value) out.close() self.response_line = ErrorCode.OK self.response_body = "ok"
from utils.redis_utils import RedisUtils from utils.logger_utils import LoggerUtils logger = LoggerUtils('customer_service.do_login').logger result = '3' header = '' try: redis = RedisUtils() form = cgi.FieldStorage() if 'account_name' in form: account_name = form.getvalue('account_name') pswd = form.getvalue('pswd') customer_service = data_customer_service.query_by_account_name( account_name) if customer_service is not None: if StringUtils.md5(pswd) != customer_service.pswd: result = '2' else: sessionid = 'session' + StringUtils.randomStr(32) while redis.exists(sessionid): sessionid = 'session' + StringUtils.randomStr(32) session = {} session['account_name'] = account_name redis.setexo(sessionid, session, 86400) header = 'Set-Cookie: session = "' + sessionid + '";path=/customer_service/' result = '0' else: result = '1' except: logger.exception(traceback.format_exc())