Exemplo n.º 1
0
def accept_connection(sock: socket):
    """
    Accepts a connection given a socket object. If the initial connection
    times out, (None, None) is returned. If the connection to get the clients
    name times out after MAX_RETIRES, then the connection is aborted.

    Parameters:
        sock (socket): The socket to connect to

    Returns:
        (socket, tuple): A tuple containing the socket object
            and address of the connecting process. Or None, None
            if the connection times out.
    """
    try:
        conn, addr = sock.accept()
    except socket.timeout:
        return (None, None)
    retries = 0
    while True:
        try:
            client_name = mp.recv_msg_protocol(conn)
            client_list.addToList(conn, client_name, DEFAULT_ROOM)
            send_help(conn)
            return (conn, addr)
        except socket.timeout:
            if retries < MAX_RETIRES:
                retries += 1
                print('Retrying...')
            else:
                # If the user takes too long to respond with a name
                # close the connection
                print(f"[CLOSING] {addr} took too long to respond")
                conn.close()
                return (None, None)
Exemplo n.º 2
0
def infinite_stream_txt_file_over_socket(file_path: str, soc: socket) -> None:
    """
    This function will send text file contents row by row over provided socket
    I've made it to test pysparks wordcount
    :param file_path:
    :param soc:
    :return:
    """
    while True:
        print('\nListening for a client at', host, port)
        conn, addr = soc.accept()
        print('\nConnected by', addr)
        try:
            print('\nReading file...\n')
            with open(file_path) as f:
                for line in f:
                    send_line_via_connection(line, conn)
                    sleep(0.02)
                print('End Of Stream.')
        except socket.error:
            print('Error Occurred.\n\nClient disconnected.\n')
        except OSError:
            destroy_socket(conn, soc)
            soc = setup_socket(host, port)
        except KeyboardInterrupt:
            destroy_socket(conn, soc)
def create_connection(sock: socket, port: int, host: str) -> socket:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # solution for: "socket.error: [Errno 98] Address already in use"
    sock.bind((host, port))
    sock.listen(5)
    connection, client_address = sock.accept() # accept connection returns tuple
    print("Got connection from ", client_address)
    return connection
def handleClient(sock: socket):

    workersock, clientaddr = sock.accept()

    log(f"Connection from {clientaddr}")
    initial = workersock.recv(1024)
    log(f"Message from {clientaddr}: {initial.decode()}")

    file = open("home.html", 'r')
    page = file.read()

    #print(page)

    workersock.send(
        str(http_classes.myResponse("OK", 200, "HTTP/1.1", page)).encode())

    # workersock.send(str(http_classes.ok).encode())
    # workersock.send(str(http_classes.htmltype).encode())
    # workersock.send(b'\n')
    # workersock.sendfile(page)
    log("Sent file: homepage.html")

    # begin page handler here
    log(f"Working with client {clientaddr}")
    while True:
        req = parseHttp(workersock, clientaddr)
Exemplo n.º 5
0
 def on_accept(self, sock: socket):
     print("getting data from {0}".format(sock.fileno()))
     conn, addr = sock.accept()
     print('accepted connection from {0}'.format(addr))
     conn.setblocking(False)
     # set it state for Any in coming message
     # register this new conn to read event
     self.selector.register(fileobj=conn, events=selectors.EVENT_READ)
Exemplo n.º 6
0
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()
Exemplo n.º 7
0
def start_server(server: socket, client_list: list):
    print("Started listening....")
    server.listen(5)
    while True:
        conn, addr = server.accept()
        print("\nNew connection from: " + str(addr))
        client_list.append(conn)
        _is_running.append(False)
        print("reverse_tcp>", end='', flush=True)
Exemplo n.º 8
0
    def __accept_wrapper(self, sock: socket):
        connection, address = sock.accept()  # Should be ready to read
        connection.setblocking(False)
        data = types.SimpleNamespace(addr=address, inb=b'', outb=b'')
        events = selectors.EVENT_READ | selectors.EVENT_WRITE
        self.__selector.register(connection, events, data=data)

        print("Connection accepted from:", address)

        # Send info to client about successful connection
        connection.sendall(b'200:Connection established.')
Exemplo n.º 9
0
def serverMonitoring(conct: socket):
    global end
    global command
    global clients
    kills = 0
    while end != False:
        try:
            client, address = conct.accept()
            obj = ClientCo()
            tmp = Thread(target=clientThread, args=[client, address, obj])
            tmp.start()
            obj.setThread(tmp)
            clients.append(obj)
        except:
            continue
    sys.exit(0)
def downlisten(socket: socket, path: str):
    childsocket, childsaddr = socket.accept()
    head = {}
    head['name'] = os.path.basename(path)
    head['size'] = os.path.getsize(path)
    head_json = json.dumps(head).encode()
    head_len = struct.pack('i', len(head_json))
    childsocket.send(head_len)
    childsocket.send(head_json)
    with open(path, 'rb') as f:
        while True:
            sen = f.read(1024)
            if len(sen) == 0:
                break
            childsocket.send(sen)
    childsocket.close()
    socket.close()
Exemplo n.º 11
0
def do_socket_logic(proxy_socket: socket, proxy_port_number):
    """
    Example function for some helper logic, in case you
    want to be tidy and avoid stuffing the main function.

    Feel free to delete this function.
    """

    proxy_socket.bind(("127.0.0.1", int(proxy_port_number)))
    proxy_socket.listen(10)
    cache = {}
    while True:
        client_socket, address = proxy_socket.accept()
        print(f"Started conn with {address}")
        start_new_thread(handle_client, (client_socket, cache, address))
    proxy_socket.close()

    pass
def accept_connections(sock: socket):
    '''
    Loop forever, accepting connections until program is manually terminated
    :param sock: The socket to bind
    :return:
    '''
    socket_id = 1

    while True:
        connection, remote_address = sock.accept()
        msg = "Accepted a new connection from {}:{}".format(
            remote_address[0], remote_address[1])
        log.info(msg)
        print(msg)

        receiver = ThreadedReceiver(connection, remote_address, socket_id)
        receiver.start()
        socket_id += 1
Exemplo n.º 13
0
def read_event(s: socket):
    """读事件处理流程"""
    # 如果是新的套接字是 主连接的套接字
    if s is sk:
        connection, client_info = s.accept()  # 该套接字监控其他连接
        connection.setblocking(False)  # 改成非阻塞
        inputs.append(connection)  # 添加该连接到监控
        message[connection] = queue.Queue()  # 给它准备好要发送的数据队列
    else:
        # 与已发送数据的客户端建立连接 获取已发送数据
        data = s.recv(1024)
        if data:
            message[s].put(data)  # 处理接收到的信息
            if s not in outputs:
                outputs.append(s)
        else:
            # 没有数据关闭连接
            socket_close(s)
Exemplo n.º 14
0
    def _accept_client_loop(self, server_socket: socket):
        logger.info(str(self), "Ready to receive requests.")
        while not self.STOP:
            if threading.active_count() > self.max_threads:
                sleep(5)  # It means that the thread will take 5 seconds maximum to return
                continue

            try:
                client_socket, _ = server_socket.accept()
                client_socket.setblocking(True)
            except socket.timeout:
                continue
            except socket.error:
                continue
            except TypeError as err:
                logger.error(str(self), "Error: \"{}\".".format(err))
                return
            exchange_thread = threading.Thread(target=self.handle_request, args=(client_socket,))
            exchange_thread.start()
        server_socket.close()
        logger.info(str(self), "Stopping server.")
Exemplo n.º 15
0
def listen_from_client(socket_name: socket):
    print(socket_name)
    try:
        (client_socket, client_address) = socket_name.accept()
        print("get connect: " + str(client_socket.getpeername()))
        print("socketserver timeout: " + str(client_socket.gettimeout()))
        client_socket.settimeout(10)
        try:

            data = client_socket.recv(4096)
            if len(data) is not 0:
                print("get data from[" + str(client_socket.getpeername) +
                      "]: " + str(data))
        except TimeoutError as te:
            print(te)
            client_socket.close()
        # data = "4D504F53010101007B22737461747573223A223030222C226D7367223A226C6F67696E2073756363657373222C" \
        #        "2264617461223A5B7B22736E223A223030323130313031303031313030303030303037227D2C7B22736E223A22" \
        #        "3030323130313031303031313030303030303038227D2C7B22736E223A22303032313031303130303131303030" \
        #        "3030303133227D2C7B22736E223A223030323130313031303031313030303030303233227D2C7B22736E223A22" \
        #        "3030323130313031303031313030303030303239227D2C7B22736E223A22303032313031303130303131303030" \
        #        "3030303837227D2C7B22736E223A223030323130313031303430313030303030323030227D5D7D4A00"
        # client_socket.send(bytes.fromhex(data))

        # client_socket.send(bytes("\nI get it!", "utf-8"))
        # sleep(5)
        send_by_random(client_socket)
        # no_response()
        try:
            client_socket.close()
        except Exception as e:
            traceback.print_exc()
            print(e)

    except InterruptedError as ie:
        traceback.print_exc()
        print(ie)
Exemplo n.º 16
0
    def ListenThread(self, sock: socket, myusername, ssocket):
        while 1:
            conn, addr = sock.accept()
            service = conn.recv(1024)
            if service == b'SWAP':
                conn.send(b'SWAP')
                client_name = conn.recv(1024).decode(encoding='utf-8')
                partner_public_mas = GetPublicKey(client_name, ssocket)
                partner_public = Point(partner_public_mas[0], partner_public_mas[1])
                secret = get_secret(int(self.__private_key), partner_public)
                msgtext = myusername + ', your shared key with %s is:\n' % client_name + str(secret.x)
                self.ShowDialog(msgtext)
                conn.close()

            elif service == b'MSG':
                conn.send(b'MSG')
                params = conn.recv(4096)
                conn.send(b'Ok')
                c_text = conn.recv(1024)
                msg, sender = FormatRecievedMessageFtomBytes(params, c_text, int(self.__private_key))
                text_to_show = myusername + ', you have recieved message from %s:\n %s' % (sender, msg)
                self.ShowDialog(text_to_show)
            conn.close()
            print('Procedure ends')
Exemplo n.º 17
0
def server_communicate(s: socket):
    client, addr = s.accept()
    serv_log.info("Получен запрос на соединение от %s" % str(addr))
    msg_from_client = recv_message(client, addr)
    server_response(msg_from_client, client)
Exemplo n.º 18
0
 def accept(s: socket):
     n = s.accept()
     IO._setupsocket(n[0])
     return n
Exemplo n.º 19
0
def accept_client_conn(serv_sock: socket, cid: int) -> socket:
    client_sock, client_addr = serv_sock.accept()
    print(f'Client #{cid} connected ' f'{client_addr[0]}:{client_addr[1]}')
    return client_sock
Exemplo n.º 20
0
def send_msg(s: socket):  # отправляет ответ клиенту;
    client, adr = s.accept()
    msg_from_client = get_msg(client)
    resp_from_server(msg_from_client, client)