Last active
August 29, 2015 14:06
-
-
Save techtonik/91a8872a32c8019bd79e to your computer and use it in GitHub Desktop.
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
# --- communicating.. networking.. --- | |
__author__ = "anatoly techtonik <[email protected]>" | |
__license__ = "MIT/Public Domain/CC0" | |
__version__ = "1.0.beta1" | |
import socket | |
IP4 = socket.AF_INET | |
UDP = socket.SOCK_DGRAM | |
class udp(object): | |
""" | |
UDP client for sending arbitrary data over network. | |
Synchronous (blocking), but supports timeouts. | |
""" | |
def __init__(self, sendto, port, data=None, timeout=60): | |
""" | |
If data is not None, send it immediately. Timeout is | |
in seconds. | |
""" | |
self.sendto = sendto | |
self.portto = port | |
self.sock = socket.socket(IP4, UDP) | |
self.sock.settimeout(timeout) | |
# counters | |
self.sent = 0 | |
self.totalsent = 0 | |
self.received = 0 | |
self.totalreceived = 0 | |
# if port=0, system chooses random one for sending | |
self.sock.bind(('', 0)) | |
if data: | |
self.send(data) | |
def send(self, data): | |
self.sent = self.sock.sendto(data, (self.sendto, self.portto)) | |
self.totalsent += self.sent | |
return self.sent | |
def read(self, size): | |
data = self.sock.recv(size) | |
self.received = len(data) | |
self.totalreceived += self.received | |
return data | |
def close(self): | |
try: | |
self.sock.shutdown(socket.SHUT_RDWR) | |
except: | |
pass | |
self.sock.close() | |
# --- /networking --- | |
if __name__ == '__main__': | |
client = udp('192.168.1.34', 5555, data="Hello") | |
print client.read(100500) | |
client.send('rawr!') | |
client.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment