Python Receiving and parse JSON Data via UDP protocol

 Python Receiving JSON Data via UDP protocol

import sys
import json
import socket

def recv_udp_msg():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.bind("127.0.0.1", 12345)
    except Exception as e:
        print(e)
        sys.exit(0)

    while True:
        try:
            msg, address = s.recvfrom(2048)
            if not msg or not address or not isinstance(msg, str):
                continue

            print("recv msg: " + str(msg))
            json_msg = json.loads(msg)
            key = json_msg.get("key")
            val = json_msg.get("val")
           
            print("key: " + str(key) + "val: " + str(val))
        except Exception as e:
            print(e)
			sys.exit(0)
			
PS: message is '{"key":"one", "val":"1"}'

Comments

Popular posts from this blog

ubus lua client method and event registration code demo/example