Klaus Demo bjoern / 9884381
Merge pull request #157 from thefab/configurable_backlog Configurable backlog (and some PEP8 fixes) Jonas Haag authored 1 year, 2 months ago GitHub committed 1 year, 2 months ago
1 changed file(s) with 15 addition(s) and 9 deletion(s). Raw diff Collapse all Expand all
33
44
55 _default_instance = None
6 LISTEN_BACKLOG = 1024
6 DEFAULT_LISTEN_BACKLOG = 1024
77
88
9 def bind_and_listen(host, port=None, reuse_port=False):
9 def bind_and_listen(host, port=None, reuse_port=False,
10 listen_backlog=DEFAULT_LISTEN_BACKLOG):
1011 if host.startswith("unix:@"):
1112 # Abstract UNIX socket: "unix:@foobar"
1213 sock = socket.socket(socket.AF_UNIX)
2223 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2324 if reuse_port:
2425 # Enable "receive steering" on FreeBSD and Linux >=3.9. This allows
25 # multiple independent bjoerns to bind to the same port (and ideally
26 # also set their CPU affinity), resulting in more efficient load
27 # distribution. https://lwn.net/Articles/542629/
26 # multiple independent bjoerns to bind to the same port (and
27 # ideally also set their CPU affinity), resulting in more efficient
28 # load distribution. https://lwn.net/Articles/542629/
2829 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
2930 sock.bind((host, port))
3031
31 sock.listen(LISTEN_BACKLOG)
32 sock.listen(listen_backlog)
3233
3334 return sock
3435
3839
3940
4041 # Backwards compatibility API
41 def listen(wsgi_app, host, port=None, reuse_port=False):
42 def listen(wsgi_app, host, port=None, reuse_port=False,
43 listen_backlog=DEFAULT_LISTEN_BACKLOG):
4244 """
4345 Makes bjoern listen to 'host:port' and use 'wsgi_app' as WSGI application.
4446 (This does not run the server mainloop.)
4547
4648 'reuse_port' -- whether to set SO_REUSEPORT (if available on platform)
49 'listen_backlog' -- listen backlog value (default: 1024)
4750 """
4851 global _default_instance
4952 if _default_instance:
5053 raise RuntimeError("Only one global server instance possible")
51 sock = bind_and_listen(host, port, reuse_port)
54 sock = bind_and_listen(host, port, reuse_port,
55 listen_backlog=listen_backlog)
5256 _default_instance = (sock, wsgi_app)
57
5358
5459 def run(*args, **kwargs):
5560 """
6974 # Called as `bjoern.run()`
7075 if not _default_instance:
7176 raise RuntimeError("Must call bjoern.listen(wsgi_app, host, ...) "
72 "before calling bjoern.run() without arguments.")
77 "before calling bjoern.run() without "
78 "arguments.")
7379
7480 sock, wsgi_app = _default_instance
7581 try: