如何修改我的python套接字服务器代码以容纳两个客户端?

问题描述 投票:0回答:1

我正在尝试将数据从我的Client_1发送到Client-2。这种传输必须通过服务器程序进行。从Client_1到服务器的数据传输成功,但是服务器无法连接到Client_2。请注意,对于我的应用程序**服务器正在像被动元素一样起作用,而不是主动元素**,即服务器没有主动发送或广播任何数据。它就像Client_1和Client_2之间的桥梁一样。

我的问题是如何修改服务器代码,以便能够将两个客户端都连接到服务器,并且应该能够将服务器中接收到的数据传输到Client_2。

下面我附上我的服务器代码::

import socket
#from threading import Thread

def server_program():

    all_connections = []
    all_address = []

    host = socket.gethostname()       ###### get the hostname ###########
    port = 5000                   ##################### initiate port no above 1024 ###############
    server_socket = socket.socket()                 ############# initiate the connection ##########e

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

            ############### configure how many client the server can listen simultaneously ################
    server_socket.listen(5)


    #def accepting_connections():
     #   for c in all_connections:
      #      c.close()

    #del all_connections[:]
    #del all_address[:]


    conn, address = server_socket.accept() 
   # socket.setblocking(1)
    all_connections.append(conn)
    all_address.append(address)
    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 housekeeping unit: " + str(data))
                # data = input(' -> ')
        conn.send(data.encode())  ########## send data to the client ###########

    conn.close() ############## close the connection ###############


if __name__ == '__main__':
    server_program()
python multithreading sockets server communication
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.