Как подключить двух клиентов к одному серверу в python? - PullRequest
0 голосов
/ 06 апреля 2020

Я пытаюсь подключить двух клиентов к моему серверу. Мой настоящий код написан для подключения одного клиента к серверу. В основном я хочу, чтобы Client_1 отправлял сообщения на сервер, а сервер мог отправлять сообщения обратно на Client_1. Сообщения, которые Client_1 будет отправлять на сервер, будут просто реплицированы или отражены в Client_2. Сам клиент_2 не должен иметь возможности отправлять сообщения на сервер. Он должен отображать только то сообщение, которое Client_1 отправляет на сервер. Ниже я передаю код сервера, код клиента_1, код клиента_2.

код сервера

import socket


def server_program():

    # get the hostname
    host = socket.gethostname()
    port = 5000  # initiate port no above 1024
    server_socket = socket.socket()  # get instance
    # look closely. The bind() function takes tuple as argument
    server_socket.bind((host, port))  # bind host address and port together

    # configure how many client the server can listen simultaneously
    server_socket.listen(2)
    conn, address = server_socket.accept()  # accept new connection
    print("Connection from: " + str(address))
    while True:
        # receive data stream. it won't accept data packet greater than 1024 bytes
        data = conn.recv(1024).decode()
        if not data:
            # if data is not received break
            break
        print("from connected user: " + str(data))
        data = input(' -> ')
        conn.send(data.encode())  # send data to the client

    conn.close()  # close the connection


if __name__ == '__main__':
    server_program()

код клиента_1

import socket


def client_program():
    host = socket.gethostname()  # as both code is running on same pc
    port = 5000  # socket server port number

    client_socket = socket.socket()  # instantiate
    client_socket.connect((host, port))  # connect to the server

    message = input(" -> ")  # take input

    while message.lower().strip() != 'bye':
        client_socket.send(message.encode())  # send message
        data = client_socket.recv(1024).decode()  # receive response

        print('Received from server: ' + data)  # show in terminal

        message = input(" -> ")  # again take input

    client_socket.close()  # close the connection


if __name__ == '__main__':
    client_program()

код клиента_2

import socket


def client_program():

    # get the hostname
    host = socket.gethostname()
    port = 5000  # initiate port no above 1024
    client_socket = socket.socket() # get instance

    client_socket.connect((host, port))      # get connected to the server                           

    #server_socket.bind((host, port))  # bind host address and port together

    while message.lower().strip() !='bye':
     client_socket.send(message.encode())  # send message
     data = client_socket.recv(1024).decode()  # receive response

     print('Received from server: ' + data)  # show in terminal

    client_socket.close()  # close the connection



if __name__ == '__main__':
    client_program()

Как мне изменить код сервера, а также код Client_2 для достижения желаемой цели. В настоящее время, когда я запускаю код Client_2, я получаю следующую ошибку.

Traceback (most recent call last):   File "socket_MobileUnit_client.py", line 26, in <module>
    client_program()   File "socket_MobileUnit_client.py", line 11, in client_program
    client_socket.connect((host, port))      # get connected to the server                            ConnectionRefusedError: [Errno 61] Connection refused
...