def _connect_to_proxy(self): """ 连接到proxy,因为有些命令要发过来 :return: """ address = os.path.join( self.app.config['IPC_ADDRESS_DIRECTORY'], self.app.config['MASTER_ADDRESS'] ) client = TcpClient(Box, address=address) while self.enable: try: if client.closed(): client.connect() except KeyboardInterrupt: break except: # 只要连接失败 logger.error('connect fail. master: %s, address: %s', self, address) time.sleep(1) continue # 读取的数据 box = client.read() if not box: logger.info('connection closed. master: %s', self) continue logger.info('box received. master: %s, box: %s', self, box) safe_call(self._handle_proxy_data, box)
def _connect_to_proxy(self): """ 连接到proxy,因为有些命令要发过来 :return: """ address = os.path.join(self.app.config['IPC_ADDRESS_DIRECTORY'], self.app.config['MASTER_ADDRESS']) client = TcpClient(Box, address=address) while True: try: client.connect() except KeyboardInterrupt: break except: # 只要连接失败 logger.error('connect fail. address: %s', address) time.sleep(1) continue # 读取的数据 box = client.read() if not box: logger.info('connection closed.') continue logger.info('box: %s', box) safe_call(self._handle_proxy_data, box)
class Connection(object): # 工作进展 work_progress = None def __init__(self, worker, address, conn_timeout): self.worker = worker # 直接创建即可 self.client = TcpClient(Task, address=address, timeout=conn_timeout) def run(self): thread.start_new_thread(self._monitor_work_timeout, ()) while self.worker.enable: try: self._handle() except KeyboardInterrupt: break except: logger.error('exc occur. worker: %s', self.worker, exc_info=True) def _monitor_work_timeout(self): """ 监控task的耗时 :return: """ while self.worker.enable: time.sleep(1) work_progress = self.work_progress if work_progress: past_time = time.time() - work_progress['begin_time'] if self.worker.app.config['WORK_TIMEOUT'] is not None and past_time > self.worker.app.config['WORK_TIMEOUT']: # 说明worker的处理时间已经太长了 logger.error('work timeout: %s / %s, request: %s', past_time, self.worker.app.config['WORK_TIMEOUT'], work_progress['request']) # 强制从子线程退出worker os._exit(-1) def _handle(self): while self.worker.enable and self.closed(): if not self._connect(): logger.error('connect fail. worker: %s, address: %s, sleep %ss', self.worker, self.client.address, self.worker.app.config['WORKER_TRY_CONNECT_INTERVAL']) time.sleep(self.worker.app.config['WORKER_TRY_CONNECT_INTERVAL']) if not self.worker.enable: # 安全退出 return self._read_message() def _connect(self): try: self.client.connect() except KeyboardInterrupt, e: raise e except:
def make_stream(self): host, port = self.url.split(':') address = (host, int(port)) client = TcpClient(self.box_class, address=address, timeout=self.timeout) client.connect() return client
def handle(uid): # client = TcpClient(Box, '192.168.1.67', 29000, timeout=None) client = TcpClient(Box, '115.28.224.64', 29000, timeout=None) client.connect() box = Box() box.cmd = 1 box.set_json(dict(uid=uid)) client.write(box) box = Box() box.cmd = 2 box.set_json(dict(uid=uid)) client.write(box) t1 = time.time() while True: # 阻塞 box = client.read() print 'time past: ', time.time() - t1 print box if not box: print 'server closed' break
def handle(uid): # client = TcpClient(Box, '192.168.1.67', 29000, timeout=None) client = TcpClient(Box, '115.28.224.64', 29000, timeout=None) client.connect() box = Box() box.cmd = 1 box.set_json(dict( uid=uid )) client.write(box) box = Box() box.cmd = 2 box.set_json(dict( uid=uid )) client.write(box) t1 = time.time() while True: # 阻塞 box = client.read() print 'time past: ', time.time() - t1 print box if not box: print 'server closed' break
def __init__(self, host, port): # 初始化log logger = logging.getLogger('main') logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setFormatter( colorlog.ColoredFormatter(constants.COLOR_LOG_FORMAT, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', })) console_handler.setLevel(logging.DEBUG) logger.addHandler(console_handler) self.logger = logger self.net_msg_queue = Queue.Queue() self.logic_msg_queue = Queue.Queue() self.tcp_client = TcpClient(GameBox, host, port) self.tcp_client.tcp_nodelay = True
def _wait_proxy(self): """ 尝试连接proxy,如果连接成功,说明proxy启动起来了 :return: """ address = os.path.join( self.app.config['IPC_ADDRESS_DIRECTORY'], self.app.config['MASTER_ADDRESS'] ) client = TcpClient(Box, address=address) while self.enable: try: client.connect() # 连接成功后,就关闭连接 client.close() return True except KeyboardInterrupt: return False except: time.sleep(0.1) continue return False
def handle(uid): client = TcpClient(Box, '127.0.0.1', 29000, timeout=None) client.connect() box = Box() box.cmd = 100 box.set_json(dict( uid=uid )) client.write(box) t1 = time.time() while True: # 阻塞 box = client.read() print 'time past: ', time.time() - t1 print box if not box: print 'server closed' break
def main(): # client = TcpClient(Box, '192.168.1.67', 29000, timeout=None) client = TcpClient(Box, '115.28.224.64', 29000, timeout=None) client.connect() box = Box() box.cmd = 3 client.write(box) t1 = time.time() while True: # 阻塞 box = client.read() print 'time past: ', time.time() - t1 print box if not box: print 'server closed' break
def handle(uid): client = TcpClient(Box, config.GATEWAY_OUTER_HOST, config.GATEWAY_OUTER_PORT, timeout=None) client.connect() box = Box() box.cmd = 2 # box.cmd = 999 box.set_json(dict(uid=uid)) client.write(box) t1 = time.time() while True: # 阻塞 box = client.read() print 'time past: ', time.time() - t1 print box if not box: print 'server closed' break
def _wait_proxy(self): """ 尝试连接proxy,如果连接成功,说明proxy启动起来了 :return: """ address = os.path.join(self.app.config['IPC_ADDRESS_DIRECTORY'], self.app.config['MASTER_ADDRESS']) client = TcpClient(Box, address=address) while self.enable: try: client.connect() # 连接成功后,就关闭连接 client.close() return True except KeyboardInterrupt: return False except: time.sleep(0.1) continue return False
# -*- coding: utf-8 -*- from netkit.contrib.tcp_client import TcpClient from reimp import Box import time client = TcpClient(Box, '127.0.0.1', 7777, timeout=10) client.connect() box = Box() box.cmd = 1 #box.cmd = 101 box.body = '我爱你' client.write(box) t1 = time.time() while True: # 阻塞 box = client.read() print 'time past: ', time.time() - t1 print box if not box: print 'server closed' break
class Connection(object): job_info = None def __init__(self, app, host, port, conn_timeout): self.app = app # 直接创建即可 self.client = TcpClient(GWBox, host, port, conn_timeout) def run(self): thread.start_new_thread(self._monitor_job_timeout, ()) while 1: try: self._handle() except KeyboardInterrupt: break except: logger.error('exc occur.', exc_info=True) def _monitor_job_timeout(self): """ 监控job的耗时 :return: """ while self.app.enable: time.sleep(1) job_info = self.job_info if job_info: past_time = time.time() - job_info['begin_time'] if self.app.job_timeout is not None and past_time > self.app.job_timeout: # 说明worker的处理时间已经太长了 logger.error('job is timeout: %s / %s, request: %s', past_time, self.app.job_timeout, job_info['request']) # 强制从子线程退出worker os._exit(-1) def _handle(self): while self.app.enable and self.closed(): if not self._connect(): logger.error('connect fail, host: %s, port: %s, sleep %ss', self.client.host, self.client.port, constants.TRY_CONNECT_INTERVAL) time.sleep(constants.TRY_CONNECT_INTERVAL) if not self.app.enable: # 安全退出 raise KeyboardInterrupt # 跟gateway要job self._ask_for_job() self._read_message() def _ask_for_job(self): gw_box = GWBox() gw_box.cmd = constants.CMD_WORKER_ASK_FOR_JOB return self.write(gw_box.pack()) def _connect(self): try: self.client.connect() except KeyboardInterrupt, e: raise e except:
# -*- coding: utf-8 -*- import sys sys.path.insert(0, '../../') from netkit.contrib.tcp_client import TcpClient from netkit.box import Box import time client = TcpClient(Box, '127.0.0.1', 9900, timeout=5) client.connect() box = Box() box.cmd = 1 # box.cmd = 101 box.body = '我爱你' client.write(box) t1 = time.time() while True: # 阻塞 box = client.read() print 'time past: ', time.time() - t1 print box if not box: print 'server closed' break
# -*- coding: utf-8 -*- from netkit.contrib.tcp_client import TcpClient from reimp import logger, Box tcp_client = TcpClient(Box, address=('127.0.0.1', 7777)) # tcp_client = TcpClient(Box, '127.0.0.1', 7777) tcp_client.connect() box = Box() box.body = '我爱你' tcp_client.write(box) while 1: # 阻塞 box = tcp_client.read() print box if not box: print 'server closed' break tcp_client.close()
def __init__(self, app, host, port, conn_timeout): self.app = app # 直接创建即可 self.client = TcpClient(GWBox, host, port, conn_timeout)
class Connection(object): # 工作进展 work_progress = None def __init__(self, worker, address, conn_timeout): self.worker = worker # 直接创建即可 self.client = TcpClient(Task, address=address, timeout=conn_timeout) def run(self): thread.start_new_thread(self._monitor_work_timeout, ()) while self.worker.enable: try: self._handle() except KeyboardInterrupt: break except: logger.error('exc occur.', exc_info=True) def _monitor_work_timeout(self): """ 监控task的耗时 :return: """ while self.worker.enable: time.sleep(1) work_progress = self.work_progress if work_progress: past_time = time.time() - work_progress['begin_time'] if self.worker.app.config[ 'WORK_TIMEOUT'] is not None and past_time > self.worker.app.config[ 'WORK_TIMEOUT']: # 说明worker的处理时间已经太长了 logger.error('work timeout: %s / %s, request: %s', past_time, self.worker.app.config['WORK_TIMEOUT'], work_progress['request']) # 强制从子线程退出worker os._exit(-1) def _handle(self): while self.worker.enable and self.closed(): if not self._connect(): logger.error( 'connect fail, address: %s, sleep %ss', self.client.address, self.worker.app.config['WORKER_TRY_CONNECT_INTERVAL']) time.sleep( self.worker.app.config['WORKER_TRY_CONNECT_INTERVAL']) if not self.worker.enable: # 安全退出 return self._read_message() def _connect(self): try: self.client.connect() except KeyboardInterrupt, e: raise e except:
def __init__(self, worker, address, conn_timeout): self.worker = worker # 直接创建即可 self.client = TcpClient(Task, address=address, timeout=conn_timeout)
# -*- coding: utf-8 -*- import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../")) import time from netkit.contrib.tcp_client import TcpClient from netkit.box import Box from web.application import create_app from share import proto from share.utils import pack_data worker_client = TcpClient(Box, '115.28.224.64', 29100) def login(): req = dict( uid=199, key='4b91e0cd5d534a8c9cb41d2517415260', ) worker_client.write(dict(cmd=proto.CMD_LOGIN, body=pack_data(req))) box = worker_client.read() print 'box:', box if not box: return False # worker_client.write(dict( # cmd=proto.CMD_SET_ALIAS_AND_TAGS, # body=pack_data(dict( # alias='dante',
# -*- coding: utf-8 -*- import sys sys.path.insert(0, '../../') from netkit.contrib.tcp_client import TcpClient from reimp import Box import time client = TcpClient(Box, '127.0.0.1', 7777, timeout=5) client.connect() box = Box() box.cmd = 1 # box.cmd = 101 box.body = '我爱你' client.write(box) t1 = time.time() while True: # 阻塞 box = client.read() print 'time past: ', time.time() - t1 print box if not box: print 'server closed' break
class Client(object): logger = None tcp_client = None # 网络层->逻辑层 net_msg_queue = None # 逻辑层->表现层 logic_msg_queue = None # 逻辑层帧数index logic_frame_index = 0 def __init__(self, host, port): # 初始化log logger = logging.getLogger('main') logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setFormatter( colorlog.ColoredFormatter(constants.COLOR_LOG_FORMAT, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', })) console_handler.setLevel(logging.DEBUG) logger.addHandler(console_handler) self.logger = logger self.net_msg_queue = Queue.Queue() self.logic_msg_queue = Queue.Queue() self.tcp_client = TcpClient(GameBox, host, port) self.tcp_client.tcp_nodelay = True def net_loop(self): # 这里将网络层作为一个单独的线程来处理了 # 实际也可以移到逻辑层里去,每帧去尝试read一次 # 先这么写吧 while True: if self.tcp_client.closed(): try: self.tcp_client.connect() except: # 重连 time.sleep(0.1) continue # 到这里就一定连接成功了 box = self.tcp_client.read() self.logger.debug('box: %r', box) if not box: # 掉线了 continue self.net_msg_queue.put(box) # 逻辑层 def logic_loop(self): while True: # 在游戏没有开始前,使用阻塞等待的方式 # 这样可以确保逻辑层主循环在server-client同时启动 box = self.net_msg_queue.get() self.logger.debug('box: %r', box) if box.cmd == cmds.CMD_EVT_GAME_START: break self.logic_frame_index = 0 frame_interval = 1.0 / constants.LOGIC_FRAME_RATE # 每一帧,从 net_msg_queue 将数据取出来 while True: self.logic_frame_index += 1 while True: # 会自己返回 try: box = self.net_msg_queue.get_nowait() except Queue.Empty: break # 需要判断帧是否与服务器一致 if box.frame_index > 0 and box.frame_index != self.logic_frame_index: # TODO 需要追赶或者延后 self.logger.warn( 'invalid logic_frame_index. logic_frame_index: %s, box: %r', self.logic_frame_index, box) self.logic_frame_index = box.frame_index if box.cmd == cmds.CMD_EVT_USER_ACTION: # 这里仅作基础演示 self.logic_msg_queue.put(box.get_json()) self.logger.debug('logic_frame_index: %s, box: %r', self.logic_frame_index, box) # do something time.sleep(frame_interval) # 表现层 def render_loop(self): frame_interval = 1.0 / constants.RENDER_FRAME_RATE while True: while True: # 会自己返回 try: msg = self.logic_msg_queue.get_nowait() except Queue.Empty: break # 作展示 self.logger.info('msg: %s', msg) time.sleep(frame_interval) def run(self): thread.start_new_thread(self.net_loop, ()) thread.start_new_thread(self.logic_loop, ()) thread.start_new_thread(self.render_loop, ()) # 等待连接 self.logger.info('waiting connect...') while self.tcp_client.closed(): time.sleep(0.1) self.logger.info('connected') while True: try: text = raw_input('please input(ready/move/hit):') if not text: continue box = GameBox() if text == 'ready': box.cmd = cmds.CMD_USER_READY self.tcp_client.write(box) elif text in ('move', 'hit'): box.cmd = cmds.CMD_USER_ACTION box.frame_index = self.logic_frame_index box.set_json(dict(action=text)) self.tcp_client.write(box) else: self.logger.warn('invalid input: %s', text) except KeyboardInterrupt: break