class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ input = "" self.host = host self.server_port = server_port # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.messRec = MessageReceiver(self, self.connection) self.run() def run(self): # Initiate the connection to the server print "Connecting to " + self.host + ":" + str(self.server_port) self.connection.connect((self.host, self.server_port)) self.messRec.start() while True: input = raw_input("") self.send_payload(input) def disconnect(self): self.disconnect pass def send_payload(self, input): data = input.split() request = data[0] content = ' '.join(data[1:]) if (content == ''): content = None payload = {"request": request, "content": content} self.connection.sendall(json.dumps(payload)) def process(self, data): msg = json.loads(data) timestamp = msg["timestamp"] sender = msg["sender"] response = msg["response"] content = msg["content"] if (response == "info"): print "INFO: " + content elif (response == "message"): print sender + ": " + content elif (response == "error"): print "<" + timestamp + ">ERROR: " + content elif (response == "history"): if (content == "start"): print "===============HISTORY===============" elif (content == "stop"): print "=====================================" else: print sender + ": " + content
def __init__(self, server, sock, ip_addr): self.sock = sock self.ip_addr = ip_addr self.active = False self.send_queue = Queue.Queue() self.receiver = MessageReceiver(self.sock) self.sender = MessageSender(self.sock) self.handler = MessageHandler() self.server = server self.last_read_time = 0
def __init__(self, host, server_port): """ This method is run when creating a new Client object """ input = "" self.host = host self.server_port = server_port # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.messRec = MessageReceiver(self, self.connection) self.run()
def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.run() self.messageReceiver = MessageReceiver.MessageReceiver( self, self.connection) self.messageReceiver.start() self.print_help() while True: request = raw_input('') if request == 'logout': self.disconnect() else: if ' ' in request: request = request.split(' ', 1) dictonary = {'request': request[0], 'content': request[1]} else: dictonary = {'request': request, 'content': None} self.send_payload(dictonary)
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) print("---Connected to server") receiver = MessageReceiver.MessageReceiver(self) receiver.start() while self.connected: self.read_and_send_data()
class ClientConnection(object): def __init__(self, server, sock, ip_addr): self.sock = sock self.ip_addr = ip_addr self.active = False self.send_queue = Queue.Queue() self.receiver = MessageReceiver(self.sock) self.sender = MessageSender(self.sock) self.handler = MessageHandler() self.server = server self.last_read_time = 0 def receive(self): message = self.receiver.receive() if message: print "SERVER %s , RECEIVE FROM %s MESSAGE %s" % ( self.server.serverName, self.sock.fileno(), repr(message.body), ) self.last_read_time = int(time.time()) self.server.enqueue((self, message)) elif self.server.isCenterServer(): self.server.removeConnection(self.sock) def send(self): try: message = self.send_queue.get(block=False, timeout=0.5) print "SERVER %s, SEND TO %s MESSAGE %s" % (self.server.serverName, self.sock.fileno(), repr(message.body)) if message: self.sock.send(message.toString()) except Exception as e: pass def enqueue(self, message): self.send_queue.put(message) self.server.epoll.modify(self.sock.fileno(), select.EPOLLIN | select.EPOLLOUT) def sendScanMessage(self): message = ScanMachineMessage(self.ip_addr) self.enqueue(message) def sendMachineInfo(self): machineInfos = collectMachineInfo() machine = Machine() machine.name = machineInfos["name"] machine.os_info = machineInfos["os_info"] machine.ip_addr = machineInfos["ip_addr"] machine.cpu_info = machineInfos["cpu_info"] machine.mem_info = machineInfos["mem_info"] machine.disk_info = machineInfos["disk_info"] self.enqueue(MachineInfoMessage(machine)) def close(self): self.sock.close()
class ClientConnection(object): def __init__(self, server, sock, ip_addr): self.sock = sock self.ip_addr = ip_addr self.active = False self.send_queue = Queue.Queue() self.receiver = MessageReceiver(self.sock) self.sender = MessageSender(self.sock) self.handler = MessageHandler() self.server = server self.last_read_time = 0 def receive(self): message = self.receiver.receive() if message: print 'SERVER %s , RECEIVE FROM %s MESSAGE %s' % ( self.server.serverName, self.sock.fileno(), repr(message.body)) self.last_read_time = int(time.time()) self.server.enqueue((self, message)) elif self.server.isCenterServer(): self.server.removeConnection(self.sock) def send(self): try: message = self.send_queue.get(block=False, timeout=0.5) print 'SERVER %s, SEND TO %s MESSAGE %s' % ( self.server.serverName, self.sock.fileno(), repr(message.body)) if message: self.sock.send(message.toString()) except Exception as e: pass def enqueue(self, message): self.send_queue.put(message) self.server.epoll.modify(self.sock.fileno(), select.EPOLLIN | select.EPOLLOUT) def sendScanMessage(self): message = ScanMachineMessage(self.ip_addr) self.enqueue(message) def sendMachineInfo(self): machineInfos = collectMachineInfo() machine = Machine() machine.name = machineInfos['name'] machine.os_info = machineInfos['os_info'] machine.ip_addr = machineInfos['ip_addr'] machine.cpu_info = machineInfos['cpu_info'] machine.mem_info = machineInfos['mem_info'] machine.disk_info = machineInfos['disk_info'] self.enqueue(MachineInfoMessage(machine)) def close(self): self.sock.close()
def __init__(self, ip_address, logger): self.__msg_senders = dict() self.__msg_receivers = dict() self.__stopSockets = list() self.__address = ip_address self.__bots = self.get_bots() self.__logger = logger self.__inbox = Inbox(self.__logger) self.__started = False for bot in self.__bots: self.__logger.debug(ip_address + " added sender and receiver for: " + bot) self.__msg_senders[bot] = MessageSender(bot, self.PORT, self.__logger) self.__msg_receivers[bot] = MessageReceiver(bot, self.__inbox, self.__logger) self.__connection = ConnectionsListener(self.__address, self.PORT, self.__msg_receivers, self.__logger)
def __init__(self): super(AgentClient, self).__init__() self.config = AgentClientConfig() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.ip_addr = self.config.server_ip self.port = self.config.server_port self.receiver = MessageReceiver(self.sock) self.handler = ScanMessageHandler() self.connection = ClientConnection(self, self.sock, self.ip_addr) self.checker = HeartBeatChecker(self.connection, self.config.heartbeat_interval) self.epoll = select.epoll() self.dispatch_queue = Queue.Queue() self.dispatcher = Dispatcher(self.dispatch_queue)
def __init__(self, ip_address, logger): self.__msg_senders = dict() self.__msg_receivers = dict() self.__stopSockets = list() self.__address = ip_address self.__bots = self.get_bots() self.__logger = logger self.__inbox = Inbox(self.__logger) self.__started = False for bot in self.__bots: bot = bot.rstrip( ) ## remove '\n' -> should have been done by get_bots(), but appearantly this didnt work self.__logger.debug(ip_address + " added sender and receiver for: " + bot) self.__msg_senders[bot] = MessageSender(bot, self.PORT, self.__logger) self.__msg_receivers[bot] = MessageReceiver( bot, self.__inbox, self.__logger) self.__connection = ConnectionsListener(self.__address, self.PORT, self.__msg_receivers, self.__logger)
def run(self): """ Creates connection between client and server. Creates threads that handles receiving and sending of data. """ # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) print "Welcome! Type in your input" try: #Create sender-thread message_sender = threading.Thread(target=self.input_loop) message_sender.daemon = True message_sender.start() #Create receiver-thread message_receiver = MessageReceiver.MessageReceiver( self, self.connection) message_receiver.start() except KeyboardInterrupt: print "losing" finally: sys.exit()
def __init__(self, thymioController, debug, experiment_name): threading.Thread.__init__(self) config = ConfigParser(cl.CONFIG_PATH) self.__address = config.address self.__port = config.port self.__thymioController = thymioController self.__tcPerformedAction = threading.Condition() self.__tcPA = False self.__msgSenders = dict() self.__msgReceivers = dict() self.__stopSockets = list() self.__stopped = False self.__previous_motor_speed = [0, 0] # simulation logging file self.__simLogger = logging.getLogger('simulationLogger') logLevel = logging.INFO if debug: logLevel = logging.DEBUG self.__simLogger.setLevel(logLevel) self.__experiment_name = experiment_name outputDir = os.path.join(cl.OUTPUT_PATH, self.__experiment_name) mkdir_p(outputDir) # self.__nextSimFilename = getNextIDPath(SIM_LOG_PATH) + '_' + time.strftime("%Y-%m-%d_%H-%M-%S") # simHandler = logging.FileHandler(os.path.join(SIM_LOG_PATH, self.__nextSimFilename + '_sim_debug.log')) self.__simulationLogFile = os.path.join(outputDir, self.__experiment_name + '_sim_debug.log') self.__simulationOutputFile = os.path.join(outputDir, self.__experiment_name + '_out.txt') self.__simulationWeightOutputFile = os.path.join(outputDir, self.__experiment_name + '_weight_out.txt') self.__simulationTempFile = os.path.join(outputDir, self.__experiment_name + '_temp.txt') simHandler = logging.FileHandler(self.__simulationLogFile) simHandler.setFormatter(cl.FORMATTER) self.__simLogger.addHandler(simHandler) self.__threadCamera = cameraVision(False, self.__simLogger) self.__inbox = Inbox(self.__simLogger) for bot in config.bots: address = bot["address"] self.__msgSenders[address] = MessageSender(address, bot["port"], self.__simLogger) self.__msgReceivers[address] = MessageReceiver(address, self.__inbox, self.__simLogger) self.__connListener = ConnectionsListener(self.__address, self.__port, self.__msgReceivers, self.__simLogger)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.messageReceiver = MessageReceiver(self, self.connection) self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.messageReceiver.start() while True: user_message = raw_input() self.send_payload(user_message) def disconnect(self): pass def receive_message(self, message): # TODO: Handle incoming message message = json.loads(message); timestamp = message['timestamp'] response = message['response'] content = message['content'] sender = message['sender'] if (response == 'history'): for history_entry in content: print(history_entry) elif (response == 'message'): print(sender + ': ' + content) else: print(content) def send_payload(self, data): request = data.split(' ',1)[0] content = data[len(request):] content = content.strip() formatted_data = {"request" : request, "content" : content} formatted_data = json.dumps(formatted_data) self.connection.send(formatted_data)
""" lastMessage = {'request': None, 'content': None} def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <<<<<<< HEAD self.connection.connect((host, server_port)) # Start listening for server messages. MessageReceiver(self, self.connection) #Start processing userinput. (Code blocked here forever) self.run() # CODE BELOW WON'T EXECUTE ======= self.connection.connect(("localhost", 9998)) MessageReceiver(self, self.connection) self.run() >>>>>>> master def run(self): print "Connected to Server..."