Last active
August 29, 2015 14:04
-
-
Save azet/09416f8e63b31e0b05d5 to your computer and use it in GitHub Desktop.
Python 3 TLS Server boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys, socket, ssl | |
def main(): | |
try: | |
PORT = int(sys.argv[1]) | |
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) | |
context.load_cert_chain(certfile="x509/server.crt", | |
keyfile="x509/server.key") | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.bind(('', PORT)) | |
sock.listen(1) # add more conns. | |
# you should really do non-blocking socket io: | |
# https://docs.python.org/3/library/ssl.html#notes-on-non-blocking-sockets | |
print("-- started listener on port", PORT) | |
while True: | |
conn, addr = sock.accept() | |
print("<< client connected:", addr) | |
stream = context.wrap_socket(conn, server_side=True) | |
try: | |
print("ohai") | |
# do stuff here | |
finally: | |
stream.shutdown(socket.SHUT_RDWR) | |
stream.close() | |
finally: | |
sock.close() | |
if __name__ == '__main__': | |
if len(sys.argv) <= 1: | |
exit(1) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment