Клиентский скрипт Chat App, возвращающий имя пользователя / сообщение других клиентов в качестве места хранения имени пользователя - PullRequest
0 голосов
/ 08 октября 2019

Всякий раз, когда я пытаюсь вернуть клиенту сообщение, которое было отправлено на мой сервер другому клиенту, вместо получения формы «имя пользователя: сообщение» от другого клиента, оно возвращается в форме:». Он также возвращает только те сообщения, которые отправили им клиенты. Не сообщения от других клиентов. Любой совет по этой проблеме будет принята с благодарностью, спасибо.

См. Код клиента ниже:

import socket
import errno
import sys

HEADER_LENGTH = 100
host = '127.0.0.1'
port = 65432

def client_socket_setup():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((host, port))
    client_socket.setblocking(False)  # Telling the recv method not to block

    return client_socket

def username(client_socket):     # Server expects the first message to be a username input by the user
    my_username = input('Username: ')  # User input of username (Not encoded in utf-8 bytes)
    username = my_username.encode('utf-8')  # Encoding the user into bytes to send
    username_header = f'{len(username):<{HEADER_LENGTH}}'.encode('utf-8')  # Defining a variable username_header and stating that the length of the username must be aligned to the left within the specified length set by HEADER_LENGTH
    client_socket.send(username_header + username)  # Sending client username info to the server

    return my_username, username_header

def message_sending(message, HEADER_LENGTH, client_socket):
    message = message.encode('utf-8')  # Encoding the message into utf-8 bytes ready to send to the server
    message_header = f'{len(message):<{HEADER_LENGTH}}'.encode('utf-8')  # Defining a variable message_header containing the information that the length of the message must be aligned to the left within the length of the username header
    client_socket.send(message_header + message)  # Encoded message now sent along with the message length info

def receiving_user(username_header, client_socket):  # Getting the username of the other client that sent the last message
    username_length = int(username_header.decode('utf-8'))  # Possibly username length
    username = client_socket.recv(username_length).decode('utf-8')

    return username

def receiving_message(client_socket):  # Getting the message from the server that the other client has sent
    message_header = client_socket.recv(HEADER_LENGTH)
    message_length = int(message_header.decode('utf-8').strip())
    username_length = message_length + 1  # Fix for the bug that was causing the invalid literal parsing error!
    message = client_socket.recv(username_length).decode('utf-8')

    return message

def send_and_recv(my_username, client_socket, HEADER_LENGTH):
    while True:
        message = input(f'{my_username} : ')  # my_username used so it is not already encoded when using it here to attach the message the user inputs

        # Sending messages and handling for an empty input i.e. no message input
        if message:
            message_sending(message, HEADER_LENGTH, client_socket)
        try:
            while True:
                # Receiving messages from other clients
                username_header = client_socket.recv(HEADER_LENGTH)

                if not len(username_header):  # Handling for an error where the username header length is not what it should be
                    print('connection closed by the server')
                    sys.exit()  # System closing the connection due to no more messages

                receiving_user(username_header, client_socket)
                receiving_message(client_socket)

                print(f'{username}: {message}')  # Printing the message from the other client along with that clients username

        # Prevernting consistent errors being raised causing issue within the program as within a non-blocking connection an error will continually be raised when no messages are coming through etc
        except IOError as e:
            if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
                print('Expecting message but not receiving ', str(e))
                sys.exit()
            continue

        # Handling for all other unexpected errors that may occur
        except Exception as e:
            print('General error ', str(e))
            sys.exit()

def main():
    client_socket = client_socket_setup()
    my_username, username_header = username(client_socket)
    send_and_recv(my_username, client_socket, HEADER_LENGTH)

if __name__ == "__main__":
    main()
...