繁体   English   中英

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

[英]How to modify my python socket server code to accommodate two clients?

我正在尝试将数据从我的 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM