# -*- coding: utf-8 -*- import time import datetime from io import BytesIO from tornado import gen from tornado import httpclient from tornado import httputil from tornado import ioloop from tornado import websocket from google.protobuf.internal import encoder from google.protobuf.internal import decoder import sys sys.path.append('proto') import msgids import Common_pb2 def getSMMsg(sm_msgid): return msgids.sc_id_hash[sm_msgid]() def newCMMsg(msgname): return msgids.cs_name_proto_hash[msgname]() def getCMMsgId(msgname): return msgids.cs_name_hash[msgname] class VirtualClient(object): def __init__(self, ws_url, account): self.ws_url = ws_url self.account = account print(self.ws_url) @gen.coroutine def co_connect(self): print("connecting, account:%s" % self.account) conn = yield websocket.websocket_connect(self.ws_url) assert conn ioloop.IOLoop.current().spawn_callback(self.co_receiveMessage, conn) print("connected, account:%s" % self.account) self.sendLogin(conn) def sendMsg(self, conn, msg): print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')) msgid = getCMMsgId(msg.DESCRIPTOR.name) gamemsg = Common_pb2.GameMsg() gamemsg.cmd = msgid gamemsg.data = msg.SerializeToString() enmsg = gamemsg.SerializeToString() f2 = BytesIO() encoder._EncodeVarint(f2.write, len(enmsg)) buff = f2.getvalue() + enmsg print(msgid, len(enmsg), len(buff), buff) conn.write_message(bytes(buff), True) print(time.time(), time.strftime('[%H:%M:%S]'), msg.DESCRIPTOR.name + ' {') print(str(msg), end='') print('}', end='') print('') def sendLogin(self, conn): msg = newCMMsg('LoginGetList_C2S_Msg') msg.loginType = 2 msg.pid = 'web' msg.serverId = 10000 msg.userId = 'default' self.sendMsg(conn, msg) msg = newCMMsg('LoginRole_C2S_Msg') msg.roleId = 687194968687664 msg.weixinadinfo = '' self.sendMsg(conn, msg) def parsePacket(self, conn, recv_buf): while len(recv_buf) > 0: # pkglen, pos = decoder._DecodeVarint(recv_buf, 0) # print(pkglen, pos, len(recv_buf)) gamemsg = Common_pb2.GameMsg() gamemsg.ParseFromString(recv_buf) # print(gamemsg) self.onReceiveUserPacket(conn, gamemsg.cmd, gamemsg.data) recv_buf = [] break def onReceiveUserPacket(self, conn, msgid, msgbody): try: print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')) msg = getSMMsg(msgid) ret = msg.ParseFromString(msgbody) #print(len(msgbody)) print(time.time(), time.strftime('[%H:%M:%S]'), msg.DESCRIPTOR.name + ' {') print(str(msg), end='') print('}') print('') except Exception as e: print('onReceiveUserPacket', e) @gen.coroutine def co_receiveMessage(self, conn): recv_buf = bytearray() while True: data = yield conn.read_message() if data is None: break else: recv_buf += data # print('receiveMessage', data) self.parsePacket(conn, recv_buf) @gen.coroutine def run(self): ioloop.IOLoop.current().spawn_callback(self.co_connect)