多处理和套接字 [英] Multiprocessing and Sockets

查看:216
本文介绍了多处理和套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用多处理和套接字来允许到同一套接字的多个连接.但是,由于我在该领域没有太多经验,所以我很难过.

I am trying to use multiprocessing and sockets to allow multiple connections to the same socket. However, I am having a real hard time because I don't have much experience in this field.

我的代码无法正常工作

def server(port, listen=10):
    connected = []
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', port))
    s.listen(listen)

    while True:

        conn, address = s.accept()
        p = multiprocessing.Process(target=server, args=(port, listen))
        p.start()
        p.join()
        command = raw_input("Command: ")
        conn.send(command)  

感谢您的帮助

推荐答案

这是因为您试图循环创建多个服务器.单台服务器足以完成您的任务,无需打开许多侦听套接字.每个本地端口可能最多由一个侦听套接字绑定-这就是为什么您看到地址使用中"错误的原因.

This is because you are trying to create multiple servers in loop. Single server is suffucient for your task, no need to open many listening sockets. Every local port may be bound by at most one listening socket -- that's why you see "address in use" error.

尝试使用Python标准 TCPServer 类,这比打扰低级套接字要方便得多.

Try out the Python standard TCPServer class, this could be much more convenient than to bother with low-level sockets.

有关线程服务器的信息,请参见此示例.

For threading server see this example.

在OS套接字级别,此方案仅需要一个侦听套接字,每次接受新连接时,它将生成一个新的套接字(这是套接字的标准方式).然后,您将在单独的线程上使用新的套接字(请注意访问线程之间共享的公共数据).

At the OS socket level, this scheme needs only one listening socket, which will spawn new socket each time when accepting a new connection (that's the standard way of socketry). Then you'll work with new socket at the separate thread (keep in mind access to common data shared among threads).

这篇关于多处理和套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆