3 from eventlet import greenio
4 from eventlet import greenpool
5 from eventlet import greenthread
6 from eventlet.green import socket
7 from eventlet.support import greenlets as greenlet
10 def connect(addr, family=socket.AF_INET, bind=None):
11 """Convenience function for opening client sockets.
13 :param addr: Address of the server to connect to. For TCP sockets, this is a (host, port) tuple.
14 :param family: Socket family, optional. See :mod:`socket` documentation for available families.
15 :param bind: Local address to bind to, optional.
16 :return: The connected green socket object.
18 sock = socket.socket(family, socket.SOCK_STREAM)
25 def listen(addr, family=socket.AF_INET, backlog=50):
26 """Convenience function for opening server sockets. This
27 socket can be used in :func:`~eventlet.serve` or a custom ``accept()`` loop.
29 Sets SO_REUSEADDR on the socket to save on annoyance.
31 :param addr: Address to listen on. For TCP sockets, this is a (host, port) tuple.
32 :param family: Socket family, optional. See :mod:`socket` documentation for available families.
35 The maximum number of queued connections. Should be at least 1; the maximum
36 value is system-dependent.
38 :return: The listening green socket object.
40 sock = socket.socket(family, socket.SOCK_STREAM)
41 if sys.platform[:3] != "win":
42 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
48 class StopServe(Exception):
49 """Exception class used for quitting :func:`~eventlet.serve` gracefully."""
53 def _stop_checker(t, server_gt, conn):
59 except greenlet.GreenletExit:
62 greenthread.kill(server_gt, *sys.exc_info())
65 def serve(sock, handle, concurrency=1000):
66 """Runs a server on the supplied socket. Calls the function *handle* in a
67 separate greenthread for every incoming client connection. *handle* takes
68 two arguments: the client socket object, and the client address::
70 def myhandle(client_sock, client_addr):
71 print("client connected", client_addr)
73 eventlet.serve(eventlet.listen(('127.0.0.1', 9999)), myhandle)
75 Returning from *handle* closes the client socket.
77 :func:`serve` blocks the calling greenthread; it won't return until
78 the server completes. If you desire an immediate return,
79 spawn a new greenthread for :func:`serve`.
81 Any uncaught exceptions raised in *handle* are raised as exceptions
82 from :func:`serve`, terminating the server, so be sure to be aware of the
83 exceptions your application can raise. The return value of *handle* is
86 Raise a :class:`~eventlet.StopServe` exception to gracefully terminate the
87 server -- that's the only way to get the server() function to return rather
90 The value in *concurrency* controls the maximum number of
91 greenthreads that will be open at any time handling requests. When
92 the server hits the concurrency limit, it stops accepting new
93 connections until the existing ones complete.
95 pool = greenpool.GreenPool(concurrency)
96 server_gt = greenthread.getcurrent()
100 conn, addr = sock.accept()
101 gt = pool.spawn(handle, conn, addr)
102 gt.link(_stop_checker, server_gt, conn)
103 conn, addr, gt = None, None, None
108 def wrap_ssl(sock, *a, **kw):
109 """Convenience function for converting a regular socket into an
110 SSL socket. Has the same interface as :func:`ssl.wrap_socket`,
111 but can also use PyOpenSSL. Though, note that it ignores the
112 `cert_reqs`, `ssl_version`, `ca_certs`, `do_handshake_on_connect`,
113 and `suppress_ragged_eofs` arguments when using PyOpenSSL.
115 The preferred idiom is to call wrap_ssl directly on the creation
116 method, e.g., ``wrap_ssl(connect(addr))`` or
117 ``wrap_ssl(listen(addr), server_side=True)``. This way there is
118 no "naked" socket sitting around to accidentally corrupt the SSL
121 :return Green SSL object.
123 return wrap_ssl_impl(sock, *a, **kw)
126 from eventlet.green import ssl
127 wrap_ssl_impl = ssl.wrap_socket
131 from eventlet.green.OpenSSL import SSL
133 def wrap_ssl_impl(*a, **kw):
135 "To use SSL with Eventlet, you must install PyOpenSSL or use Python 2.6 or later.")
137 def wrap_ssl_impl(sock, keyfile=None, certfile=None, server_side=False,
138 cert_reqs=None, ssl_version=None, ca_certs=None,
139 do_handshake_on_connect=True,
140 suppress_ragged_eofs=True, ciphers=None):
141 # theoretically the ssl_version could be respected in this line
142 context = SSL.Context(SSL.SSLv23_METHOD)
143 if certfile is not None:
144 context.use_certificate_file(certfile)
145 if keyfile is not None:
146 context.use_privatekey_file(keyfile)
147 context.set_verify(SSL.VERIFY_NONE, lambda *x: True)
149 connection = SSL.Connection(context, sock)
151 connection.set_accept_state()
153 connection.set_connect_state()