def run(self): try: client = TcpClient("localhost", 4444) while 1: raw_input("Press Enter to continue...\n") client.sendToServer("Client - send to Server") except KeyboardInterrupt: print "Shutdown requested...exiting\n" except Exception: traceback.print_exc(file=sys.stdout) raw_input("Press Enter to continue...\n") sys.exit(0)
def run(self): while not self.stopflag: #logger.debug("waiting for client...") try: client, addr = self.sock.accept() tcpClient = TcpClient(self._id, client, addr, socktypes.TCP_CLIENT_REMOTE) sigObject.emit(signals.SIG_REMOTE_TCP_CLIENT_CONNECTED, tcpClient, self._id, tcpClient.getId(), addr[0], addr[1]) logger.debug("new client %s:%d connected" % addr) tcpClient.start() self.tcpClients[tcpClient.getId()] = tcpClient except socket.timeout: pass logger.debug("server stopped")
def reset(self, ip=None, port=None): self.client and self.client.close() self.ip = ip or self.ip self.port = port or self.port self.client = TcpClient(self.ip, self.port, self) self.status = ChannelClient.CS_INIT self.cancelTimer()
def client_start(): client = TcpClient() # TODO: Settings client.set_host("192.168.3.50") client.set_port(445) client.connect() return client
def __init__(self, ip, port, rpcService): super(ChannelClient, self).__init__() self.rpcService = rpcService self.ip = ip self.port = port self.logger = LogManager.getLogger('MarsRpc.ChannelClient') self.client = TcpClient(self.ip, self.port, self) self.status = ChannelClient.CS_INIT self.timer = None self.callback = None
def start(self): self.loadconfig() self.tcpClient = TcpClient((self.host, self.port), self.dispatcher) logicThread = threading.Thread(target=logic_thread_handler, name="logic", args=[self.dispatcher]) cmdloopThread = threading.Thread(target=cmdloop_thread_hendler, name="cmdloop", args=[self]) networkThread = threading.Thread(target=network_thread_handler, name="network", args=[self.tcpClient]) logicThread.start() networkThread.start() cmdloopThread.start() networkThread.join() logicThread.join() cmdloopThread.join()
class Controller(Cmd): def __init__(self, host, port, CmdHandlerClass): Cmd.__init__(self) self.use_rawinput = False self.dispatcher = BaseCommandDispatcher(CmdHandlerClass) self.dispatcher.SetConnectCallback(self.OnConnect) # 连接服务器成功后,发登陆命令 def OnConnect(self, conn): req = pp.request("login", {"type":"controller", "name":self.name}) conn.send(req) # 加载配置 def loadconfig(self): config = cp.ConfigParser() config.read("./config/controller.config") sectionName = "NormalConfig" self.name = config.get(sectionName, "name") self.host = config.get(sectionName, "host") self.port = int(config.get(sectionName, "port")) def start(self): self.loadconfig() self.tcpClient = TcpClient((self.host, self.port), self.dispatcher) logicThread = threading.Thread(target=logic_thread_handler, name="logic", args=[self.dispatcher]) cmdloopThread = threading.Thread(target=cmdloop_thread_hendler, name="cmdloop", args=[self]) networkThread = threading.Thread(target=network_thread_handler, name="network", args=[self.tcpClient]) logicThread.start() networkThread.start() cmdloopThread.start() networkThread.join() logicThread.join() cmdloopThread.join() def preloop(self): logger.info(u"*"*80) logger.info(u"\n") logger.info(u"Welcome to use EasyDeploy controller!") logger.info(u"\n") logger.info(u"*"*80) self.printhelp() def printhelp(self): # 打印命令规则 print u"Usage:\n" h = u"\t 1. ed {cmd} [arg1 [arg2]..]\ \n\t 2. Print 'exit' to exit" print h def postloop(self): print(u"Bye!") ############################################################ # 具体命令行输入处理 do_xxx ############################################################ def do_ed(self, line): if line is None: return inputs = line.split() cnt = len(inputs) if cnt < 1: print u"命令无效: \"", line , u"\"" return # 分割出命令和参数 cmd = inputs[0] param = {} if cnt > 1: for i in range(1, cnt): param[str(i)] = inputs[i] req = pp.request("agent_cmd", {"cmd":cmd, "param":param}) #print req self.tcpClient.send(req) def do_ping(self, line): print "do_ping" req = pp.request("ping", {}) if req is not None: self.tcpClient.send(req) def do_exit(self, line): import os os._exit(0)
class ChannelClient(object): # CONNECT STATUS CS_INIT = 0 CS_CONNECTING = 1 CS_FAILED = 3 CS_SUCCESSED = 4 def __init__(self, ip, port, rpcService): super(ChannelClient, self).__init__() self.rpcService = rpcService self.ip = ip self.port = port self.logger = LogManager.getLogger('MarsRpc.ChannelClient') self.client = TcpClient(self.ip, self.port, self) self.status = ChannelClient.CS_INIT self.timer = None self.callback = None def getPeername(self): return self.client.getPeername() def reset(self, ip=None, port=None): self.client and self.client.close() self.ip = ip or self.ip self.port = port or self.port self.client = TcpClient(self.ip, self.port, self) self.status = ChannelClient.CS_INIT self.cancelTimer() def cancelTimer(self): if self.timer and not self.timer.cancelled and not self.timer.expired: self.timer.cancel() self.timer = None def _checkConnection(self): if self.status != ChannelClient.CS_SUCCESSED: self.callback and self.callback(None) self.status = ChannelClient.CS_FAILED self.logger.error('connection timeout') def connect(self, callback, timeout): self.client.asyncConnect() self.callback = callback self.status = ChannelClient.CS_CONNECTING self.timer = Timer.addTimer(timeout, self._checkConnection) def disconnect(self): self.client and self.client.disconnect() def handleNewConnector(self, connector): self.logger.info('handle new connector %s', connector.socket.getpeername()) rpcChannel = RpcChannel(self.rpcService, connector) self.status = ChannelClient.CS_SUCCESSED self.callback and self.callback(rpcChannel) def handleConnectorFailed(self, connector): self.cancelTimer() self.status = ChannelClient.CS_FAILED self.callback and self.callback(None) self.logger.error('connector failed')
#-*- encoding: gb2312 -*- import datetime #import socket import threading import logging from oneStock import * from stgytools import * import MsgPacket from TcpClient import TcpClient gtcpCli = TcpClient() cliName = 'stgy1' pname = 'ben1' mktName = 'fut1' runFlag = runningFlag() class strategyBench(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.onlyOneMsg = 0 self.stockDict = {} self.clOrdeId = 0 self.timeDeq = [] self.timesec = 0 self.timeasc = '' self.canRecvQuote = 1 now = datetime.datetime.now() self.nowDay = now.strftime('%Y-%m-%d') logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%H:%M:%S',