UDP 服务器解析 JSON 个对象的数据结构 python

Data structure for UDP Server parsing JSON objects in python

我有一个 UDP 服务器侦听线程中的传入流量。消息来自外部设备,格式为 JSON,例如 {"_id": "0x00", "status": "on"}。此信息需要由 UDP 处理程序解析并存储在对象字典中(如果 _id 存在则更新)目前我可以接收和解析 JSON,但不确定如何存储此数据或处理它正确。我想在 UDP 处理程序中使用队列和处理队列的单独消息处理程序,但不确定这样做是否正确。

请注意:我重写了代码,省略了一些语法等

# I create a node server thread in the main of my program with IP/PORT

class NodeServer(threading.Thread):
    def __init__():
        self.server = UDPServer((address, port), UDPHandler)

    def run():
        self.server.serve_forever()

class UDPServer(socketserver.ThreadingUDPServer):
    allow_reuse_address = True

class UDPHandler(socketserver.BaseRequestHandler):
    data_q = queue.Queue()

    handler = NodeHandler(data_q)
    handler.start()

    def handle():
        try:
            # receive the message from client
            data = self.request[0].decode("UTF-8")

            # check if it's in json format

            # HANDLE THE MESSAGE
            self.data_q.put(data)

            # stop the thread
            self.handler.join()
            # send an "ACK" msg back to the client
      except: Exception as e:
            #handle

class NodeHandler(threading.Thread):
    table = NodeTable()

    def __init(data_q):
        self.data_q = data_q

    def handle():
      # get the string message from the queue (filled by the UDPHandler)
      msg = self.data_q.get()

      # check if the "_id" field exists in the current node table

      # if it exists in the table, find it, update the fields from json

      # otherwise, if it's a new "_id": create a new node
      json_msg = json.parse(msg)
      node = Node(json_msg["_id"])
      # set other node parameters from the json object, status etc

      # update the node table with the new information from the message
      table.put(nd)
      #
    def join():
        # join thread

class NodeTable():
  # the table is a dictionary with ID and a Node object, ie {0x01: Node}
  table = {}
  def put(_id, node):
      self.table[_id] = node

  def get(_id):
      return self.table[_id]

class Node():
    id = 0
    def __init__(id):
        self.id = id
        # new node
    # other node functions

谢谢!

1) 你可以实现一个 UDP 服务器来处理传入的消息 使用这些代码行更简单的无限循环:

 import socket

 def udp_server(udp_ip, udp_port, ...):
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   sock.bind((upd_ip, upd_port))
   while True:
     data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
     ...process data...

有关详细信息,请参阅 https://wiki.python.org/moin/UdpCommunication 和讨论。

udp_server 的参数是 udp IP 和端口,等等 服务器需要与之交互的其他数据结构。

把它放到它自己的线程中是很容易完成的 有:

 import threading

 t = threading.Thread(target = udp_server, args = (...))
 t.start()

2) NodeTable class 只是 python 字典的包装器, 但似乎你想让多个线程访问它 同时。在那种情况下,你应该阅读这个 SO 答案: (link).

取决于服务器线程之外的其他线程可以做什么 您可能需要也可能不需要锁的节点字典。

总而言之,我将如何编写代码:

 def main():
   nodes = {}     # use a simple dict for storing the nodes
   lock = RLock() # if you need this
   # pass nodes and lock to server thread and start it
   t = threading.Thread(target = udp_server, args = (udp_ip, udp_port, nodes, lock))
   t.start() 
   ...

此时udp服务器运行主线程可以访问节点 table 通过变量 nodes.

添加新节点是否需要通知主线程 节点 table?那么也许队列就是您想要的。你会 1) 创建它 在 main() 和 2) 中传递给 udp_server:

 def main()
   nodes = {}     # use a simple dict for storing the nodes
   lock = RLock() # if you need this
   q = Queue()    # create a Queue and pass it to the udp server
   # pass nodes and lock to server thread and start it
   t = threading.Thread(target = udp_server, args = (udp_ip, udp_port, nodes, lock, q))
   t.start() 
   # process entries from the Queue
   while True:
     item = q.get()
     ... process item...

并且在 udp 服务器函数中 ...process data... 将把一些东西放到队列中:

   while True:
     data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
     ...json decode, etc. ...
     q.put(...)