Created
July 16, 2015 15:34
-
-
Save mieciu/df4ed74fed4b98f77371 to your computer and use it in GitHub Desktop.
Python TCP and UDP sockets within context manager
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
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