Skip to content

Instantly share code, notes, and snippets.

@mieciu
Created July 16, 2015 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mieciu/df4ed74fed4b98f77371 to your computer and use it in GitHub Desktop.
Save mieciu/df4ed74fed4b98f77371 to your computer and use it in GitHub Desktop.
Python TCP and UDP sockets within context manager
import socket
from contextlib import contextmanager
@contextmanager
def tcp_connection_to(*args, **kwargs):
s = socket.create_connection(*args, **kwargs)
yield s
s.close()
@contextmanager
def udp_connection():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
yield s
s.close()
MY_SERVER = ('localhost', 5000)
some_data = bytes("Hello.")
with tcp_connection_to(MY_SERVER) as conn:
conn.send(some_data)
with udp_connection() as conn:
conn.sendto(some_data, MY_SERVER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment