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 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 HandleDisconnect(self, client : socket): if(client in self.clientSockets): client.shutdown() # inform the client we're closing connection? client.close() # close socket self.clientSockets.remove(client) # stop thinking about the client return
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 socket_close(s: socket): """关闭一个套接字""" if s in outputs: outputs.remove(s) inputs.remove(s) s.close() del message[s]
def terminate(conn: socket) -> None: """ terminates the connection of a socket :param conn: connection to be terminated """ conn.close()
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 game_in_progress_loop(s: socket): while True: package = rp(s.recv(256)) request_type = package.get("rt") message = package.get("msg") if request_type == RT.start_turn.value: # Player start turn print("msg from server: ", message) coordinate = raw_input(": ") while not valid_coordinate(coordinate=coordinate): coordinate = raw_input(": ") s.sendto(create_message(RT.send_coord.value, coordinate), ADDR) elif request_type == RT.hit.value: # Player hit draw_opponents_map(coordinate=coordinate, hit=True) print("msg from server: ", message) coordinate = raw_input(": ") while not valid_coordinate(coordinate=coordinate): coordinate = raw_input(": ") s.sendto(create_message(RT.send_coord.value, coordinate), ADDR) elif request_type == RT.miss.value: # Player missed draw_opponents_map(coordinate=coordinate, hit=False) print("msg from server: ", message) elif request_type == RT.msg.value: # Message from server print("msg from server: ", message) s.close()
def client_thread(conn: socket, addr): question = json.dumps({ 'hour': time.localtime().tm_hour + 3, 'minute': time.localtime().tm_min, 'nick': 'server', 'message': 'What\'s your name?' }) conn.send(bytes(question, encoding='utf8')) username = conn.recv(1024).decode("utf-8") if len(username) == 0 or username[0:14] != token: remove(curr_connection=conn) conn.close() greeting_message = "Welcome to the club " + username[14:] greeting = json.dumps({ 'hour': time.localtime().tm_hour + 3, 'minute': time.localtime().tm_min, 'nick': 'server', 'message': greeting_message }) try: conn.send(bytes(greeting, encoding='utf8')) except Exception as e: print("User not auth") conn.close() remove(conn) broadcast_meeting(username=username[14:], connection=conn) try: while True: message = conn.recv(1024).decode("utf-8") auth(message=message) if len(message) > 0: message_to_send = json.dumps({ 'hour': time.localtime().tm_hour - 3, 'minute': time.localtime().tm_min, 'nick': username[14:], 'message': message[14:] }) print("cool") broadcast(message_to_send, conn) else: conn.close() remove(conn) except ConnectionResetError: print("Connection lost") conn.close() remove(conn) except Exception as e: print(str(e)) conn.close() remove(conn)
def change_admin_password(client_socket: socket, user_info: dict, msg: dict) -> dict: user_info = Scripts.AdminRequests.change_self_password( msg["Content"], user_info) client_socket.sendall(json.dumps(Scripts.Responses.fine()).encode()) client_socket.close() Scripts.LogWriter.admin_password_changed(msg["Time"]) return user_info
def resetCon(sock1: socket): global clientAddress try: sent = sock1.sendto(serverResetCon().encode(), clientAddress) except OSError: print('Caught OSError') finally: sock1.close()
def kick_telnet_client(s: socket) -> None: try: s.close() print("I: client kicked") telnet_sockets_going_out.remove(s) telnet_sockets_going_in.remove(s) except ValueError: pass
def serve_client(self, sock: socket): # Wait for desired state self.logger.waiting_for_setup() setup = StateSetup.FromString(sock.recv()) state_handle = self.make_state(setup) self.logger.making_state(state_handle.state_handle, setup.n) sock.send(state_handle.SerializeToString()) # Apply operations running_job = True try: while running_job: self.logger.waiting_for_operation(state_handle.state_handle) op = WorkerOperation.FromString(sock.recv()) self.logger.running_operation(state_handle.state_handle, op) returned_data = None if op.HasField("close"): running_job = False else: with self.pool_lock: pool = self.job_pools[state_handle.state_handle] returned_workers, returned_data = pool.send_op(op) if returned_workers: self.logger.returning_workers( state_handle.state_handle, len(returned_workers)) with self.worker_lock: self.free_workers.extend(returned_workers) self.logger.done_running_operation(state_handle.state_handle, op) conf = WorkerConfirm() conf.job_id = state_handle.state_handle if returned_data: conf.measure_result.CopyFrom(returned_data) sock.send(conf.SerializeToString()) except IOError as e: self.logger.log_error("Unknown exception: {}".format(e)) conf = WorkerConfirm() conf.error_message = str(e) try: sock.send(conf.SerializeToString()) except IOError as e: self.logger.log_error("Error sending error code: {}".format(e)) finally: with self.pool_lock: pool = self.job_pools[state_handle.state_handle] returned_workers = pool.close(state_handle.state_handle) self.logger.returning_workers(state_handle.state_handle, len(returned_workers)) with self.worker_lock: self.free_workers.extend(returned_workers) self.logger.closing_state(state_handle.state_handle) sock.close()
def start(proxy_socket: socket): cache = Cache() try: while True: client, address = proxy_socket.accept() threading.Thread(target=client_handler, args=(client, address, cache)).start() except KeyboardInterrupt: proxy_socket.close()
def handle_client(self, client_socket: socket): '''开始接受并处理数据''' addr, port = client_socket.getsockname() # 处理函数 self.chat(client_socket) client_socket.close() print("[-] Connection {}:{} closed".format(addr, port))
def receive_server_response(s: socket, response: HttpRequestInfo) -> list: s.send(response.to_byte_array(response.to_http_string())) received_data = s.recv(Constants.MAX_RECEIVE) server_response = [] while len(received_data) > 0: server_response.append(received_data) received_data = s.recv(Constants.MAX_RECEIVE) s.close() return server_response
def __readAll(self,client: socket): try: response = client.recv(128) if response is not None and response != b"": self.response(client,str(response)) else: self.__close(client) except: client.close() pass
def _handle_request(self, client: socket, address): try: data = self._retrieve_request_data(client) request = HttpRequest(data) response = HttpResponse(request) Dispatcher.dispatch(response) client.send(response.render()) client.close() except: sys.exit()
def handle_client(self, client_socket: socket, data: bytes, buffer=1024): '''开始接受并处理数据''' addr, port = client_socket.getsockname() # 接收数据 request = client_socket.recv(buffer) self.data.append(request.decode('utf-8')) # print("[*] Recieved: {} \t from {}:{}".format(str(request),addr,port)) # 发送数据 client_socket.send(data) client_socket.close() print("[-] Connection {}:{} closed".format(addr, port))
async def echo(connection: socket, loop: AbstractEventLoop) -> None: try: while data := await loop.sock_recv(connection, 1024): print('got data!') if data == b'boom\r\n': raise Exception("Unexpected network error") await loop.sock_sendall(connection, data) except Exception as ex: logging.exception(ex) finally: connection.close()
def handle_request(self, socket_client: socket): if not self._socks_sub_negotiation(socket_client): return request = self._socks_request(socket_client) if request is None: return link, connection_id, socket_link = request self._exchange_with_client(socket_client, socket_link) socket_client.close() link.close_connection(connection_id) return
def exit(self, sock: socket): """ Closes a clients connection safely :sock: Socket of the connection to close on """ self.logging.debug("Closing sockets and preparing to exit") print("\nClosing connections") sock.send(bytes("{}, EXIT, 0, 0.0.0.0".format(self.vertex_id), "utf-8")) sock.close()
def send_message(sock: socket, secret: int) -> None: while True: msg = input("> ") encrypt_client = AESCipher(msg, str(secret)).encrypt() try: sock.sendall(encrypt_client.encode("utf-8")) except socket.error: print("[ ERROR: Could not send message ]") break print(f"[ Connection closed ]\n") sock.close()
def accept_socket(sock: socket, addr, REQUEST_MAX_LENGTH=1024 * 1024): ori_request = sock.recv(REQUEST_MAX_LENGTH) request = Request(ori_request.decode('utf-8'), addr) response = handle_request(request) after_handle_response(response) response_bytes = response.data() response_headers_bytes = response.headers_responses() sock.send(response_headers_bytes) sock.send(response_bytes) sock.close() log(' >>>>[INFO] '+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' Accept Connection %s:%s %s' % (addr[0], addr[1], request.signature,))
def deal_client(sock: socket, addr): print("Accept new connection from %s" % (addr,)) sock.send(b'Hello I am Server') while True: data = sock.recv(1024) time.sleep(1) if not data or data.decode('utf-8') == 'exit': break print('---> %s' % (data.decode('utf-8'))) sock.send(("Loop_Msg %s ! " % (data.decode('utf-8'))).encode('utf-8')) sock.close() print("Connection from %s closed" % addr)
def run_eight_ball(sock: socket): while True: question = input( "I am a sexy Magic 8-Ball: ask me almost anything or nothing to exit\nQ: " ) if question == "": sock.close() break sock.send(question.encode()) response = sock.recv(1024) print("A: " + str(response.decode()) + "\n")
def on_incoming_data(self, sock : socket): if sock is server: #accept a client else: #the client has sent data data = sock.recv(self.buffer_size).decode("utf-8") if data: self._on_data_func(data) else: if sock in outputs: outputs.remove(sock) inputs.remove(sock) sock.close()
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 accept_socket(sock: socket, addr): ori_request = sock.recv(REQUEST_MAX_LENGTH) # parse original request to the special format for human request = Request(ori_request.decode('utf-8'), addr) log("Accept new http request: %s" % request.signature) log(" original http request:\n", ori_request) response = handle_request(request) after_handle_response(response) response_bytes = response.source_view() log('Send http response:', response_bytes) sock.send(response_bytes) sock.close()
def client(client_socket: socket): while True: yield ('read', client_socket) request = client_socket.recv(4096) if not request: break else: response = "client response -- " yield ('write', client_socket) client_socket.send(response) client_socket.close()
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 handleClient(clientSocket:socket): received = clientSocket.recv(1024) print('Received data', received) clientSocket.send('hello') clientSocket.close()