Python socket.accept 非阻塞? [英] Python socket.accept nonblocking?

查看:164
本文介绍了Python socket.accept 非阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以以非阻塞方式使用 python 的 socket.accept() 来简单地运行它并让我检查它是否有任何新连接?我真的不想使用线程.谢谢.

Is there a way I can use python's socket.accept() in a non-blocking way that simply runs it and lets me just check if it got any new connections? I really don't want to use threading. Thanks.

推荐答案

你可能想要像 select.select() 这样的东西(参见 文档).您为 select() 提供三个套接字列表:要监视可读性、可写性和错误状态的套接字.当新客户端正在等待时,服务器套接字将是可读的.

You probably want something like select.select() (see documentation). You supply select() with three lists of sockets: sockets you want to monitor for readability, writability, and error states. The server socket will be readable when a new client is waiting.

select() 函数将阻塞,直到套接字状态之一发生变化.如果不想永远阻塞,可以指定可选的第四个参数 timeout.

The select() function will block until one of the socket states has changed. You can specify an optional fourth parameter, timeout, if you don't want to block forever.

这是一个愚蠢的回声服务器示例:

Here is a dumb echo server example:

import select
import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', 8888))
server_socket.listen(5)
print "Listening on port 8888"

read_list = [server_socket]
while True:
    readable, writable, errored = select.select(read_list, [], [])
    for s in readable:
        if s is server_socket:
            client_socket, address = server_socket.accept()
            read_list.append(client_socket)
            print "Connection from", address
        else:
            data = s.recv(1024)
            if data:
                s.send(data)
            else:
                s.close()
                read_list.remove(s)

Python 还为支持它们的平台提供了 epollpollkqueue 实现.它们是 select 的更高效版本.

Python also has epoll, poll, and kqueue implementations for platforms that support them. They are more efficient versions of select.

这篇关于Python socket.accept 非阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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