gpt4 book ai didi

python - Python 中的多处理和套接字

转载 作者:太空狗 更新时间:2023-10-30 00:33:32 26 4
gpt4 key购买 nike

我试图让多处理和套接字编程一起工作,但是,我被困在了这一点上。问题是,我收到此错误:

  File "multiprocesssockserv.py", line 11, in worker
clientsocket = socket.fromfd(clientfileno, socket.AF_INET, socket.SOCK_STREAM)
error: [Errno 9] Bad file descriptor

导致错误的完整代码如下:

import multiprocessing as mp
import logging
import socket

logger = mp.log_to_stderr(logging.WARN)

def worker(queue):
while True:
clientfileno = queue.get()
print clientfileno
clientsocket = socket.fromfd(clientfileno, socket.AF_INET, socket.SOCK_STREAM)
clientsocket.recv()
clientsocket.send("Hello World")
clientsocket.close()

if __name__ == '__main__':
num_workers = 5
socket_queue = mp.Queue()
workers = [mp.Process(target=worker, args=(socket_queue,)) for i in
range(num_workers)]

for p in workers:
p.daemon = True
p.start()

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('',9090))
serversocket.listen(5)
while True:
client, address = serversocket.accept()
socket_queue.put(client.fileno())

编辑:我正在使用 socket.fromfd,因为我不能将套接字放入队列 :) 我需要一种方法来以某种方式从不同的进程访问相同的套接字。这是我的问题的核心。

最佳答案

在研究了一段时间之后,我决定从不同的角度来解决这个问题,下面的方法似乎对我有用。

import multiprocessing as mp
import logging
import socket
import time

logger = mp.log_to_stderr(logging.DEBUG)

def worker(socket):
while True:
client, address = socket.accept()
logger.debug("{u} connected".format(u=address))
client.send("OK")
client.close()
if __name__ == '__main__':
num_workers = 5

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('',9090))
serversocket.listen(5)

workers = [mp.Process(target=worker, args=(serversocket,)) for i in
range(num_workers)]

for p in workers:
p.daemon = True
p.start()

while True:
try:
time.sleep(10)
except:
break

关于python - Python 中的多处理和套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8545307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com