Created
February 24, 2018 20:33
-
-
Save Gydo194/a7f4bd29159f8ca8be898324584c4058 to your computer and use it in GitHub Desktop.
python_udp_pubsub_server
This file contains hidden or 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 logging | |
from pprint import pprint | |
import socket | |
import json | |
HOST = "127.0.0.1" | |
PORT = 1234 | |
BUFFER_SIZE = 2 * 1024 #2Kb buffer | |
log = logging.getLogger("UDP_IR") | |
FORMAT_CONS = '%(asctime)s %(name)-12s %(levelname)8s\t%(message)s' | |
logging.basicConfig(level=logging.DEBUG, format=FORMAT_CONS) | |
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) | |
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) | |
funcs = {} | |
clients = {} | |
def convert(data): | |
try: | |
print "Loading json from: "+data | |
arr = json.loads(data) | |
print "Res:" | |
pprint(arr) | |
return arr | |
except Exception as e: | |
log.error("Error loads-ing json. %r",str(e)) | |
return {} | |
def handler(context,client): | |
print "handler called" | |
if not "action" in context: | |
log.error("No action defined as of context") | |
return | |
try: | |
if context["action"] in funcs: | |
log.info("CALLING FUNCTION %s" % context["action"]) | |
funcs[context["action"]](context,client) #call function | |
else: | |
log.error("function does not exist: %s" % context["action"]) | |
except Exception as ex: | |
log.error("Cannot call function, ex dmp: %r",ex) | |
def listen(): | |
log.debug("Listening..") | |
(data,addr) = s.recvfrom(BUFFER_SIZE) | |
log.info("Received: %s" % data) | |
handler(convert(data),addr) | |
log.debug("finished handling") | |
def funcBootstrap(): | |
log.debug("Running function handler bootstrap") | |
funcs["reg"] = regClient | |
funcs["send"] = send | |
#server funcs | |
def regClient(context,client): | |
try: | |
print "regclient dumping client passed" | |
pprint(client) | |
#dump client over here | |
clients[context["name"]] = client | |
except Exception as ex: | |
log.error("Error while registering client. %r",ex) | |
def send(context,client): | |
log.info("sending message ") | |
try: | |
log.debug("client object: %r",clients[context["name"]]) | |
s.sendto(context["message"],clients[context["name"]]) | |
except Exception as sendex: | |
log.error("Error sending: %r",sendex) | |
def main(): | |
funcBootstrap() | |
s.bind((HOST,PORT)) | |
log.info("starting") | |
while True: | |
listen() | |
if __name__ == "__main__": | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment