def deal_client(newSocket: socket, addr): global queue_ status = False while True: sleep(1) try: if status and not queue_.empty(): submissionId_proId = queue_.get() print(submissionId_proId) newSocket.send(("judge|%s" % submissionId_proId).encode()) data = newSocket.recv(1024) recv_data = data.decode() if recv_data == 'gotten': status = False else: queue_.put(submissionId_proId) else: newSocket.send('get_status'.encode()) data = newSocket.recv(1024) recv_data = data.decode() if recv_data == "ok": status = True print(addr, status) except socket.error: newSocket.close() except Exception as e_: newSocket.close() print(e_)
def send(self, channel: socket, other_node: NeighbourNode, token: Token): log(self.pid, ": sending a token of type ", token.type_, " from ", token.src_pid, " in ", token.direction, "direction") time.sleep(self.channel_delay) channel.sendto(json.dumps(token.__dict__).encode("utf-8"), (other_node.ip, other_node.port))
def terminate(conn: socket) -> None: """ terminates the connection of a socket :param conn: connection to be terminated """ conn.close()
def recv_data(app: str, sock: socket): """ Get response from socket with proper start/end headers :app: Which application is receiving the data :sock: Socket to pull data from :return: String of data received """ logger = logging.getLogger(app) data = "" data_start = "-- DATA START --" data_end = "-- DATA END --" data_header = sock.recv(16) if data_header.decode("utf-8") == data_start: logger.debug("Getting response: [{}]".format( data_header.decode("utf-8"))) else: logger.error("Error with get response, aborting") logger.error("data_header: [{}]".format(data_header.decode("utf-8"))) return None while True: data += sock.recv(1024).decode("utf-8") if data.endswith(data_end): # Strip "data_end" from data data = data[:-len(data_end)] logger.debug("Data received: [{}]".format(data)) return data else: logger.debug("Incomplete data received so far: [{]]".format(data)) return None
def close_port(skt: socket): # essaie et si le port n'est pas connecté, on fait juste le fermer. Autrement on coupe la connexion avant de fermer try: skt.shutdown(socket.SHUT_RDWR) except OSError: pass skt.close()
def send_gossip__heartbeat(self,current_machine_socket:socket, current_machine_IP_address:str, current_port:int, membership_dict:dict, number_of_members_to_gossip): """ This function sends gossip heartbeats to the specified number Parameters: current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address current_port : The current machine's port number membership_dict : The membership dictionary of the system """ for ip in membership_dict.keys(): membership_dict[ip][1] = str(membership_dict[ip][1]) gossip__heartbeat_msg_dict = {'Type' : "gossip__heartbeat", 'IP_address' : current_machine_IP_address, 'Timestamp' : (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'Port' : str(current_port), 'Membership_dict' : json.dumps(membership_dict) } gossip_heartbeat_msg_json = json.dumps(gossip__heartbeat_msg_dict) data = (gossip_heartbeat_msg_json).encode('utf-8') for i in range(number_of_members_to_gossip): iprand, = random.sample(membership_dict.keys(), 1) while (iprand == current_machine_IP_address):#if iprand is current_machine_IP_address, reselect iprand, = random.sample(membership_dict.keys(), 1) target_ip_address = iprand target_port = int(membership_dict[target_ip_address][3]) self.bytes_sent += (sys.getsizeof(gossip_heartbeat_msg_json) / 1024) current_machine_socket.sendto(data, (target_ip_address, target_port))
def handshake(s: socket, game_id: int) -> int: f""" Sends the handshake for rps. :param game_id: {int} :param s: {socket} :return: {int} uid of player """ # Start with 4 'empty' bytes empty_byte = 0 confirmation = 1 rule_set = 1 payload_length = 2 protocol_version = 1 packet = [ empty_byte, empty_byte, empty_byte, empty_byte, confirmation, rule_set, payload_length, protocol_version, game_id ] s.sendall(bytes(packet)) uid = get_uid(s) return uid
def handle_reply(current_socket: socket, request: str) -> dict: """ Отправляет сообщение на сервер, получает и обрабатывает ответ :param current_socket: сокет для общения с сервером :param request: сформированный запрос на сервер :return: ответ о проверке лабораторной работы """ logger.info("Sending request on server to check the lab...") logger.debug("The request is: {request}".format(request=request)) current_socket.send(request.encode()) try: reply_data: dict = json.loads(current_socket.recv(1024).decode()) logger.info("Got a reply from server!") message_type: int = reply_data.pop('messageType') if message_type == MessageType.WRONG_REQUEST.value: raise SystemError( "We've got problems: an error \n {error} \n occurred with a key '{key}'" .format(error=reply_data['text'], key=reply_data['key'])) elif message_type == MessageType.SERVER_ERROR.value: raise SystemError("Server has got a problem: {error}".format( error=reply_data['errorMessage'])) elif message_type == MessageType.DEFAULT_ANSWER.value: logger.debug("The lab was successfully checked, moving on..") return reply_data except TypeError as err: raise TypeError( "Error reading data from server: {error} \n with traceback {tb}". format(error=err, tb=traceback.format_exc()))
def handle_outgoing_msgs(self, s: socket): if self.server_state == E4ServerState.NEW__: # request devices list print('Getting list of devices...') s.send(msg(E4ServerCommand.DEVICE_LIST__)) self.server_state = E4ServerState.WAITING__ elif self.server_state == E4ServerState.NO_DEVICES__: print('No devices found!') exit(1) elif self.server_state == E4ServerState.DEVICES_FOUND__: # connect to device print('Connecting to device...') s.send( msg("%s %s" % (E4ServerCommand.DEVICE_CONNECT__, self.device_id))) self.server_state = E4ServerState.WAITING__ elif self.server_state == E4ServerState.CONNECTED_TO_DEVICE__: # pause streaming initially print('Initializing...') s.send(msg("%s ON" % E4ServerCommand.PAUSE__)) self.server_state = E4ServerState.WAITING__ elif self.server_state == E4ServerState.READY_TO_SUBSCRIBE__: # subscribe to streams stream = self.stream_ids[self.sub_streams] print('Subscribing to stream: %s' % stream) s.send( msg("%s %s ON" % (E4ServerCommand.DEVICE_SUBSCRIBE__, stream))) self.server_state = E4ServerState.WAITING__ elif self.server_state == E4ServerState.SUBSCRIBE_COMPLETED__: # begin streaming data print('Requesting data') s.send(msg("%s OFF" % E4ServerCommand.PAUSE__)) self.server_state = E4ServerState.STREAMING__
def message_handle(server: classmethod, client: socket): """ socketBlh的消息处理. """ global num_online_client, online_client client_id = '' client.sendall("连接服务器成功!".encode(encoding='utf8')) while True: buff = str(client.recv(1024), encoding='UTF-8') if '[id]:' in buff: tmp = buff.split(':') client_id = str(tmp[1]) dm_logger(server, f'客户端上线! 客户端id: {client_id}\n') online_client.append(client_id) num_online_client += 1 time.sleep(0.5) dm_logger(server, f'目前在线数量: {num_online_client}\n') elif len(buff) == 0: try: g_conn_pool.remove(client) online_client.remove(client_id) client.close() except: pass dm_logger(server, '有一个客户端下线了! 客户端id: {0}\n'.format(client_id)) try: online_client.remove(client_id) except: pass num_online_client -= 1 break else: dm_logger(server, "客户端消息: {0}\n".format(buff))
def recv_ack(self, s: socket, e: threading.Event): buffer = 2 while True: ack_b, addr = s.recvfrom(buffer) ack = int.from_bytes(ack_b, 'big') logging.debug('recv ack {0}'.format(ack)) with self.mutex: if ack == self.send_base: if not self.next_seq > len(self.pac_lis) - 1: s.sendto(self.pac_lis[self.next_seq], self.dst_addr) self.send_base += 1 if self.next_seq < len(self.pac_lis) - 1: self.next_seq += 1 logging.debug('Forward Window {0}'.format( list(range(self.send_base, self.next_seq)))) e.set() elif ack > self.send_base: self.send_base = ack + 1 self.next_seq = self.send_base logging.debug('Reset Window {0}'.format( list(range(self.send_base, self.next_seq)))) e.set() if ack == len(self.pac_lis) - 1: break
def send_all_to_all__heartbeat(self, current_machine_socket: socket, current_machine_IP_address: str, current_port: int, membership_dict: dict): """ This functions sends all to all heartbeats. Parameters: current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address current_port : The current machine's port number membership_dict : The membership dictionary of the system """ heartbeat_dict = { 'Type': "all_to_all_heart_beat", 'IP_address': current_machine_IP_address, 'Port': current_port, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } heartbeat_json = json.dumps(heartbeat_dict) for target_ip_address in membership_dict.keys(): target_port = membership_dict[target_ip_address][3] if (target_ip_address == current_machine_IP_address): continue self.bytes_sent += (sys.getsizeof(heartbeat_json) / 1024) current_machine_socket.sendto((heartbeat_json).encode('utf-8'), (target_ip_address, target_port))
def make_connection(mysocket: socket) -> None: ''' This is an information of connection. After made, socket connect to the address. ''' connect_address = ('circinus-32.ics.uci.edu', 4444) mysocket.connect(connect_address)
def client_send(client_socket: socket): while True: print( '1. register topic, 2. remove topic, 3. keep alive, 4. get match list, 5. publish' ) command = input() if command == '1': type = input('type:') name = input('name:') period = input('period:') msg = f'register_topic {type} {name} {period}' elif command == '2': name = input('name:') msg = f'remove_topic {name}' elif command == '3': type = input('type:') name = input('name:') msg = f'keep_alive {type} {name}' elif command == '4': msg = f'get_match_list' elif command == '5': name = input('name:') filename = 'text' value = input('message:') filesize = len(value) msg = f'publish {name} {filename} {str(filesize)} {value}' else: print('Wrong command.') client_socket.send(msg.encode('utf-8'))
def read(s: socket): while True: x: str = input("> ").ljust(4, '0') s.sendall(x.encode()) if x[0] == 'q': running = False break
def ascii_str_by_socket(sock: socket): """Messages are received through sock and converted into ascii equivalent strings using str_to_ascii_str, and sent back via sock Args: sock: socket The socket connection by which communication with the client is implemented (AF_INET, SOCK_STREAM) Returns: (none) Raises: (none) """ msg_out: str = ' ' msg_in: str = ' ' while True: msg_in = sock.recv(DEFAULT_BUFFER_SIZE) if (msg_in.decode(UTF_8) == END_OF_FILE): break print('[S]: Message received from client: \'{}\''.format( msg_in.decode(UTF_8))) msg_out = str_to_ascii_str(msg_in.decode(UTF_8), '_') print('[S]: Message sending to client: \'{}\''.format(msg_out)) sock.send(msg_out.encode(UTF_8))
def send_quit_to_socket(self, target_ip_address: str, target_port: int, current_machine_socket: socket, current_machine_IP_address: str, current_port: int): """ This functions sends a quit message to the introducer machine. Parameters: target_ip_address (string) : The IP_address of the machine to send the quit request to. target_port (int) : The machine's port number current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address timestamp : The timestamp of the message sent. """ quit_to_send = { 'Type': "Quit", 'IP_address': current_machine_IP_address, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } quit_to_send_json = json.dumps(quit_to_send) self.bytes_sent += (sys.getsizeof(quit_to_send_json) / 1024) current_machine_socket.sendto((quit_to_send_json).encode('utf-8'), (target_ip_address, target_port))
def connect_socket(self, s: socket, host_ip: str, port: int, destination: int): ''' Method takes a socket and connection parameters and connects to that destination. @Param: s:: socket to be used to establish connection host_ip:: destination IP port:: destination Port destination:: node ID of destination. ''' counter = 0 while True: try: # attempt to connect socket to other node s.connect((host_ip, port)) #print("out socket from self ", self.nodeID, " to ", destination, " at ", self.out_sockets[destination]) print("Out socket connected to :", destination) break except socket.error: # while the connection fails, wait, and retry if counter == 12: print("Connecting to node ", destination, " at ", host_ip, port, ' ......') counter = 0 # debug print statemet to see how in socket thread count changes #for sthread in self.in_socket_threads: # print(type(sthread)) counter += 1 sleep(.25) continue
def crack_user(sock: socket) -> str: # Define a list of common admin usernames. common_usernames = [ 'admin', 'Admin', 'admin1', 'admin2', 'admin3', 'user1', 'user2', 'root', 'default', 'new_user', 'some_user', 'new_admin', 'administrator', 'Administrator', 'superuser', 'super', 'su', 'alex', 'suser', 'rootuser', 'adminadmin', 'useruser', 'superadmin', 'username', 'username' ] # Attempt to login via the specified socket with each of the common admin usernames. for usr in common_usernames: # Create a dictionary of the current credentials being tested. credentials = {"login": usr, "password": "******"} # Create a JSON string from the credentials, encode it and send it to the specified socket. sock.send(dumps(credentials).encode()) # Decode the site's response, load a dictionary from that JSON string and retrieve the value paired with the # 'result' key. result = loads(sock.recv(1024).decode())['result'] # If the result is 'Wrong password!', the correct username was found. if result == 'Wrong password!': return usr # If none of the common admin usernames are the correct one, raise an exception. raise AssertionError('Unable to determine admin username.')
def send_ack_msg_to_socket(self, target_ip_address: str, target_port: int, current_machine_socket: socket, current_machine_IP_address: str, current_port: int, membership_dict: dict): """ This function sends an acknowledge message to the specified machine. Parameters: target_ip_address (string) : The IP_address of the specified machine to send the acknowledge message to. target_port (int) : The specified machine's port number current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address timestamp : The timestamp of the message sent. """ for ip in membership_dict.keys(): membership_dict[ip][1] = str(membership_dict[ip][1]) ack_msg_dict = { 'Type': "Ack", 'Process_id': (str(os.getpid())).strip(), 'IP_address': current_machine_IP_address, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'Port': str(current_port), 'Membership_dict': json.dumps(membership_dict) } ack_msg_json = json.dumps(ack_msg_dict) self.bytes_sent += (sys.getsizeof(ack_msg_json) / 1024) current_machine_socket.sendto((ack_msg_json).encode('utf-8'), (target_ip_address, target_port))
def make_play(self, s: socket, invitation: str): proposed_play = input(invitation) play_ord = ord(proposed_play) s.sendall(play_ord.to_bytes(1, 'big')) return int(proposed_play)
def send_delete_ack(self, current_machine_socket: socket, master_port: int, master_IP_address: str, sdfs_file_name: str, current_machine_IP_address: str): """ This function sends a delete acknowledgement to the master once file is deleted Parameters: current_machine_socket (socket) : This machine's socket master_IP_address (string): the master's ip address or the ip address of the node containing the file master_port (integer) : the master's port number or the port number of the node containing the file file_name (string) : name of the file to be deleted """ delete_ack = { 'Type': "delete_ack", 'IP_who_delete_file': current_machine_IP_address, 'sdfs_file_name': sdfs_file_name, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } delete_ack_json = json.dumps(delete_ack) current_machine_socket.sendto((delete_ack_json).encode('utf-8'), (master_IP_address, master_port))
def setup_io_between_server_client(mysocket: socket) -> None: ''' This is to setup 'read' and 'write' ''' input_stream = mysocket.makefile('r') output_stream = mysocket.makefile('w') return input_stream, output_stream
def send_join_request_to_socket(self, target_ip_address: str, target_port: int, current_machine_socket: socket, current_machine_IP_address: str, current_port: int): """ This function sends a join request to the introducer machine. Parameters: target_ip_address (string) : The IP_address of the introducer machine to send the join request to. target_port (int) : The introducer's port number current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address timestamp : The timestamp of the message sent. """ join_request_dict = { 'Type': "Join_req", 'Process_id': (str(os.getpid())).strip(), 'IP_address': current_machine_IP_address, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'Port': str(current_port) } join_request_json = json.dumps(join_request_dict) self.bytes_sent += (sys.getsizeof(join_request_json) / 1024) current_machine_socket.sendto((join_request_json).encode('utf-8'), (target_ip_address, target_port))
def send_window(self, s: socket, e: threading.Event): while True: if self.send_base > len(self.pac_lis) - 1 or self.next_seq > len( self.pac_lis) - 1: break if self.next_seq < self.send_base + self.win_size: for i in range(self.win_size): s.sendto(self.pac_lis[self.next_seq], self.dst_addr) with self.mutex: self.next_seq += 1 if self.next_seq >= len(self.pac_lis) - 1: with self.mutex: self.next_seq = len(self.pac_lis) - 1 break logging.debug('ReBuild Window {0}'.format( list(range(self.send_base, self.next_seq)))) e.clear() logging.debug('Wait') if not e.wait(self.timeout): logging.debug('Timeout detected') for i in range(self.send_base, self.next_seq): s.sendto(self.pac_lis[i], self.dst_addr) logging.debug('ReSend pkt {0}'.format(i))
def send_file(filename: str, conn: socket) -> None: f = open(filename, 'rb') l = f.read(1024) while(l): conn.send(l) l = f.read(1024) f.close()
def handle_client(conn: socket, client_address: tuple): """Handle connection with client.""" print(f"[Client connecting] Client is trying to connect") connected, user = handle_initial_connection(conn, connected_users) print( f"[Client connected] Client with {client_address} and nick '{user.name}' connected " ) while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) message = conn.recv(msg_length).decode(FORMAT) print(f"[Client send] ({client_address}) {user}: {message}") if message == DISCONNECT_MESSAGE: connected = False else: message = f"{message}" send_messages_to_mailing_list(connected_users, conn, user.name, message) conn.close() connected_users.remove(user) print( f"[Client disconnected] Client with {client_address} disconnected. Connection closed." )
def button_click(self, gas:str, tempers:list, heattimes:list, staytimes:list, sock:socket, process_info:tuple): count = len(tempers) local_tempers = list(map(str, tempers)) local_heattimes = list(map(str, heattimes)) local_staytimes = list(map(str, staytimes)) heattime = ' '.join(local_heattimes) staytime = ' '.join(local_staytimes) temper = ' '.join(local_tempers) if self.now_start_button: msg = self.base_opt + ' ' + str(count) + ' ' + temper + ' ' + heattime + ' ' + staytime + ' ' + gas else: msg = self.base_opt msg_byte = msg.encode() sock.sendall(msg_byte) loader = loadingGif.LoadingGif() recv_msg = sock.recv(1024).decode() loader.stopAnimation() if self.now_start_button and not self.is_process_wokring: process_info["id"], process_info["starttime"] = recv_msg.split('+') self.custom_toggle() for elem in self.disable_list: elem.setEnabled(not self.now_start_button) for elem in self.able_list: elem.setEnabled(self.now_start_button)
def send_juice_start_request_to_master( self, current_machine_socket: socket, master_port: int, master_IP_address: str, juice_exe: str, num_juices: str, sdfs_intermediate_filename_prefix: str, sdfs_dest_filename: str, delete_input: str): juice_start_request_to_master = { 'Type': "juice_start_request_to_master", 'juice_exe': juice_exe, 'num_juices': num_juices, 'sdfs_intermediate_filename_prefix': sdfs_intermediate_filename_prefix, 'sdfs_dest_filename': sdfs_dest_filename, 'delete_input': delete_input, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } juice_start_request_to_master_json = json.dumps( juice_start_request_to_master) current_machine_socket.sendto( (juice_start_request_to_master_json).encode('utf-8'), (master_IP_address, master_port))
def send_get_request_to_master(self, current_machine_socket: socket, requestor_ip: str, master_port: int, master_IP_address: str, sdfs_file_name: str, local_file_name_to_store: str): """ This function sends a get request Parameters: current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the requester machine's IP address current_port (integer) : the requester machine's port master_IP_address (string): the master's ip address or the ip address of the node containing the file master_port (integer) : the master's port number or the port number of the node containing the file file_name (string) : name of the file to be deleted """ get_request = { 'Type': "get_request_to_master", 'sdfs_file_name': sdfs_file_name, 'local_file_name_to_store': local_file_name_to_store, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'requestor_ip': requestor_ip } get_request_json = json.dumps(get_request) current_machine_socket.sendto((get_request_json).encode('utf-8'), (master_IP_address, master_port))
def send_payload(sock: socket, payload: PayloadEncoder or PayloadEventMessages, address=None): if sock is None or sock._closed or payload is None: print("[x] Unable to send payload [Payload %s, Socket %s]" % (payload, socket)) return if isinstance(payload, PayloadEventMessages): payload = payload.value if address is None: sock.sendall(encode_to_json(payload.content()).encode("utf-8")) else: sock.sendto(encode_to_json(payload.content()).encode("utf-8"), address)
def setup_game(s: socket) -> None: try: socket_in = s.makefile('r') socket_out = s.makefile('w') socket_out.write('I32CFSP_HELLO '+user_id+'\r\n') socket_out.flush() reply = socket_in.readline() socket_out.write('AI_GAME\r\n') socket_out.flush() reply = socket_in.readline() print(reply) except: print('Connection Failed. Closing the socket.') s.close()
def AI(s: socket, command: str, column_number: int) -> None: '''receive actions from server''' if command == 'A': s.send(str('DROP ' + str(column_number) + '\r\n').encode(encoding = 'utf-8')) c = s.recv(4096).decode(encoding = 'utf-8') reply_A = s.recv(4096).decode(encoding = 'utf-8') return reply_A elif command == 'B': s.send(str('POP ' + str(column_number) + '\r\n').encode(encoding = 'utf-8')) c = s.recv(4096).decode(encoding = 'utf-8') reply_B = s.recv(4096).decode(encoding = 'utf-8') return reply_B
def receive_payload(sock: socket): data = str(sock.recv(1024), "utf-8") if data is not None and len(data) > 0: received = decode_from_json(data) return build_payload(received)
def handleClient(clientSocket:socket): received = clientSocket.recv(1024) print('Received data', received) clientSocket.send('hello') clientSocket.close()