为什么多处理在python中不起作用

2024-06-16 13:27:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个聊天应用程序,其中使用了多处理。 代码太大,所以我只发送代码的主要问题,谢谢你的帮助

Code

import socket,select
from multiprocessing import Process
HEADER_LENGTH = 10
IP = socket.gethostbyname(socket.gethostname())
PORT = 1234
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen()
sockets_list = [server_socket]
clients = {}





def Run_Server():
    def receive_message(client_socket):

        try:
            message_header = client_socket.recv(HEADER_LENGTH)

            if not len(message_header):
            return False

            message_length = int(message_header.decode('utf-8').strip())

            return {'header': message_header,'data':client_socket.recv(message_length)}

        except:



            return False
    while True:

        read_sockets, _, exception_sockets = select.select(sockets_list[],sockets_list)



        for notified_socket in read_sockets:


            if notified_socket == server_socket:


                client_socket, client_address = server_socket.accept()


                user = receive_message(client_socket)

   
                if user is False:
                    continue

 
                sockets_list.append(client_socket)

                clients[client_socket] = user

                print('Accepted new connection')

            else:

                message = receive_message(notified_socket)


                if message is False:
                    print('Closed connection ')

   
                    sockets_list.remove(notified_socket)


                    del clients[notified_socket]

                        continue

                user = clients[notified_socket]

                print(f'Received message')

  
                for client_socket in clients:


                    if client_socket != notified_socket:

                        client_socket.send(user['header'] )


        for notified_socket in exception_sockets:

            sockets_list.remove(notified_socket)

            del clients[notified_socket]

if __name__ =='__main__' :
    p1= Process(target=Run_Server)
    p1.start()
    p1.join()

输出 空白 但它应该加载服务器,这样我就可以使用它了。我看到很多这样的问题,但无法纠正错误。请告诉我出了什么问题。我在没有p1.join()的情况下尝试了事件,但仍然无法工作,请帮助我


Tags: clientfalsemessageifserversocketselectsockets