def sendMsg(self, msg="None"): msg = self.__typeArea.dump('1.0', tk.END) if msg[0][0] == 'text' and len(msg[0][1]) > 0: self.__typeArea.delete('1.0', tk.END) utils.send(self.clientSocket, (const.MSG, self.token, '{0}:\t{1}'.format( self.user, msg[0][1])))
def resciveThread(self, client, ClientKey): #在服务开启期间一直运行 while self.isOpen: try: #接受数据 cmd, token, data = recv(client) if cmd == const.MSG and len(data) > 0: #有数据 #打印出来看 #print("\"{0}\" :{1}".format(ClientKey,bytes.decode(data))) #传给所有客户端 for _clientIp, _client in self.clientsList.items(): send(_client, (const.MSG, '0' * 32, data)) else: #没数据,估计是网络有问题,断掉 #客户端不能发空消息不然也会断掉 client.close() del self.clientsList[ClientKey] break except (ConnectionAbortedError, ConnectionResetError): #客户端主动把连接中断了 if self.accepting: del self.clientsList[ClientKey] break
def run(self): while True: try: receive(self.conn, PACKAGE_LEN) except ConnectionClosedException: break # Error is expected as client closes connection wh done send(self.conn, ACK_MSG)
def acceptingThread(self): while self.accepting: try: #一直等待新的客户端 newClient, newOne = self.serverSocket.accept() #等到了 #看在不在黑名单里 if newOne[0] in self.blackIpList: #在黑名单里 if self.blackIpList[newOne[0]] >= 3: #还失败了三次 newClient.close() #看看是谁 #print("refuse {0} connect".format(newOne[0])) #继续等 continue #看看客户端是不是用51000来连的 if (False): #不是断掉 newClient.close() #记在小本本里 if (self.blackIpList.__contains__(newOne[0])): self.blackIpList[newOne[0]] += 1 else: self.blackIpList[newOne[0]] = 1 else: #IP+端口号产生一个键 newkey = "{0}:{1}".format(newOne[0], newOne[1]) #添加一个客户键值对 self.clientsList[newkey] = newClient session = self.login(newClient, newkey) if session: #开启这个客户的读取消息线程 send(newClient, (const.LOGIN, '0' * 32, session.token)) threading.Thread(target=self.resciveThread, args=(newClient, newkey)).start() else: self.disconnect(newClient, newkey) except OSError: break
def stop(self): """ Stop the listener. """ self._logger.info("Listener stopping") with self._runLock: if not self.running: self._logger.warn("Listener already stopped") return self.running = False self._logger.debug("Bumping the thread out of the blocking accept") try: utils.send(self._address, self._port, "") except Exception, e: self._logger.exception(e) self._thread.join() self._server_socket.close() self._logger.info("Listener stopped")
def run_direct_ping(self): """ Executes direct ping count times and prints output """ # handshaking send(self.sock, DIRECT_PING) rcv = receive(self.sock, ACK_LEN) if rcv != ACK_MSG: raise ValueError( str.format("Expected %s, received %s", (ACK_MSG, rcv))) self.out_mgr.print_file_version() self.out_mgr.print_operation(True, False, False) self.out_mgr.print_server(self.dest_address) self.out_mgr.print_client(self.address) # direct ping packet_loss = 0 rtt_list = [] for i in range(self.count): before = dt.now() send(self.sock, get_random_string(PACKAGE_LEN)) rcv = receive(self.sock, ACK_LEN) delta = dt.now() - before if rcv != ACK_MSG: raise ValueError(f"Expected {ACK_MSG}, received {rcv}") delta = round( (delta.seconds + delta.microseconds / 1000000.0) * 1000, 1) if delta >= (TIMEOUT_SECONDS * 1000): packet_loss += 1 continue rtt_list.append(delta) if self.verbose: self.out_mgr.print_latest_message(PACKAGE_LEN, self.dest_address, i + 1, delta) self.out_mgr.print_statistics(self.dest_address, self.count, self.count - packet_loss, rtt_list)
def register(self): ''' Register this notifier client with the server. ''' self._stop_registration_timer() self._logger.info('Registering user %s with host %s', self._username, self._address) command = parser.encode(requests.RegistrationRequest(self._address, self._username)) try: self._logger.debug('Registering with {0} on port {1}'. format(self._server_address, self._server_port)) utils.send(self._server_address, self._server_port, command) except Exception, e: self._logger.warn('Could not register ({0}); ' 'will retry in {1} second(s)'. format(e, self._retry_period)) self._start_registration_timer()
def connectServer(self): try: self.clientSocket.connect((config.severIp, config.prot)) utils.send(self.clientSocket, (const.LOGIN, self.token, '{0}\t{1}'.format( self.user, self.password))) try: cmdType, token, data = utils.recv(self.clientSocket, False) if cmdType == const.LOGIN: self.token = data #print("recive token %s"%data) self.isOpen = True return True else: return False except: return False except ConnectionRefusedError as ex: print(ex.strerror) self.isOpen = False return False
def run_proxy_ping(self): """ Executes proxy ping count times and prints output """ # handshaking send(self.sock, PROXY_PING) format_count = '0' + str(COUNT_LEN) + 'd' send(self.sock, format(self.count, format_count)) format_dest_addr = '0' + str(DEST_ADDR_LEN) + 'd' send(self.sock, format(len(self.proxy_address), format_dest_addr)) send(self.sock, self.proxy_address) sig = receive(self.sock, ACK_LEN) if sig != ACK_MSG: print("Unable to connect to proxy server", file=sys.stderr) return self.out_mgr.print_file_version() self.out_mgr.print_operation(False, False, True) self.out_mgr.print_server(self.dest_address) self.out_mgr.print_client(self.address) packet_loss = 0 rtt_list = [] for i in range(self.count): _sig = receive(self.sock, ACK_LEN) if _sig != ACK_MSG: print("Connection between server and proxy ended " + "unexpectedly", file=sys.stderr) return rtt = float(receive(self.sock, RTT_LEN)) if rtt == DISCARDED_PCK_RTT: packet_loss += 1 continue rtt_list.append(rtt) if self.verbose: self.out_mgr.print_latest_message(PACKAGE_LEN, self.dest_address, i + 1, rtt) self.out_mgr.print_statistics(self.dest_address, self.count, self.count - packet_loss, rtt_list)
def run(self): for i in range(self.count): initial_dt = dt.now() try: send(self.proxy_conn, get_random_string(PACKAGE_LEN)) receive(self.proxy_conn, ACK_LEN) except ConnectionClosedException as e: send(self.client_conn, ERR_MSG) raise ConnectionClosedException(str(e)) final_dt = dt.now() send(self.client_conn, ACK_MSG) delta = final_dt - initial_dt if delta.seconds >= TIMEOUT_SECONDS: send(self.client_conn, str(DISCARDED_PCK_RTT)) continue delta = round( (delta.seconds + delta.microseconds / 1000000.0) * 1000, 1) delta = "{:07.1f}".format(delta) send(self.client_conn, delta)
def run(self): for i in range(self.count): initial_dt = dt.now() send(self.conn, get_random_string(PACKAGE_LEN)) receive(self.conn, ACK_LEN) final_dt = dt.now() delta = final_dt - initial_dt if delta.seconds >= TIMEOUT_SECONDS: send(self.conn, str(DISCARDED_PCK_RTT)) continue delta = round( (delta.seconds + delta.microseconds / 1000000.0) * 1000, 1) delta = "{:07.1f}".format(delta) send(self.conn, delta) self.conn.close()
def run_reverse_ping(self): """ Executes reverse ping count times and prints output """ # handshaking send(self.sock, REVERSE_PING) sig = receive(self.sock, ACK_LEN) if sig != ACK_MSG: raise ValueError( str.format("Expected %s, received %s", (ACK_MSG, sig))) _format = '0' + str(COUNT_LEN) + 'd' send(self.sock, format(self.count, _format)) self.out_mgr.print_file_version() self.out_mgr.print_operation(False, True, False) self.out_mgr.print_server(self.dest_address) self.out_mgr.print_client(self.address) packet_loss = 0 rtt_list = [] for i in range(self.count): try: receive(self.sock, PACKAGE_LEN) send(self.sock, ACK_MSG) rtt = float(receive(self.sock, RTT_LEN)) if rtt == DISCARDED_PCK_RTT: packet_loss += 1 continue rtt_list.append(rtt) if self.verbose: self.out_mgr.print_latest_message(PACKAGE_LEN, self.dest_address, i + 1, rtt) except ConnectionClosedException: break self.out_mgr.print_statistics(self.dest_address, self.count, self.count - packet_loss, rtt_list)
def __init__(self, conn): self.client_conn = conn self.count = int(receive(conn, COUNT_LEN)) addr_len = int(receive(conn, DEST_ADDR_LEN)) dest_addr_split = receive(conn, addr_len).split(':') dest_addr = (dest_addr_split[0], int(dest_addr_split[1])) # create socket and connect to proxy self.proxy_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # handshaking with proxy sv to begin direct ping try: self.proxy_conn.connect(dest_addr) send(self.proxy_conn, DIRECT_PING) receive(self.proxy_conn, ACK_LEN) except (gaierror, ConnectionRefusedError, ConnectionClosedException) \ as e: send(self.client_conn, ERR_MSG) raise ConnectionClosedException(str(e)) send(self.client_conn, ACK_MSG)
def disconnect(self): utils.send(self.clientSocket, (const.LOGOUT, self.token, ""))
def __init__(self, conn): send(conn, ACK_MSG) self.count = int(receive(conn, COUNT_LEN)) self.conn = conn
def __init__(self, conn): self.conn = conn send(conn, ACK_MSG)