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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- Multiple sockets for clients to connect to
- How to get the background from multiple images by
- Evil ctypes hack in python
You probably want something like
select.select()
(see documentation). You supplyselect()
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.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:
Python also has
epoll
,poll
, andkqueue
implementations for platforms that support them. They are more efficient versions ofselect
.You can invoke the
setblocking(0)
method on the Socket to make it non-blocking. Look into the asyncore module or a framework like Twisted.