How to react to network events

المشرف العام

Administrator
طاقم الإدارة
I am in the process of writing a Plugin which should react to some data (XML-Format) sent via a socket connection. Since I have never worked with IPC in terms of python before and my knowledge of IPC is, sadly, pretty limited, I'd like to ask you for some ideas and/or help.

So far, my first shot at the problem was to implement a simple non-blocking echo-server inside of QGIS just to have something similar running. The code of the echo-server is basically taken from here and a little modified as follows:

def start_listener(self): PORT = 10000 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((socket.gethostname(), PORT)) server_socket.listen(5) # Incoming Sockets inputs = [server_socket] # Outgoing Sockets outputs = [] message_queues = {} while 1: # "poll" every 0.25 Seconds readable, writeable, exceptional = select.select(inputs, outputs, [], 0.25) # Sockets ready to be read for s in readable: if s is server_socket: client_socket, client_address = s.accept() client_socket.setblocking(0) inputs.append(client_socket) message_queues[client_socket] = Queue.Queue() else: data = s.recv(1024) # if data received if data: message_queues.put(data) if s not in outputs: outputs.append(s) else: if s in outputs: outputs.remove(s) s.close() del message_queues # sockets ready to write for s in writeable: try: next_msg = message_queues.get_nowait() except Queue.Empty: outputs.remove(s) else: s.send(next_msg) # Sockets in Error-State for s in exceptional: inputs.remove(s) if s in outputs: outputs.remove(s) s.close() del message_queues The Code is launched as a Thread as QGIS will block otherwise. Ultimately the stream contains data which cause QGIS to select given features and pan to those features. My exact question now is: What is the best point of loading such a server? If I'm correct there are two options, namely startup.py or somewhere in the plugin (maybe modify __init__ ?). If I load the server inside the startup.py, is there a way to get a reference to it so that the data can be processed in the plugin-code? Or is there even a better way to solve this problem?

Another problem with the given code is, that it causes a pretty high CPU-load when a connection is handled and the load does not drop after the client has closed the connection.



أكثر...
 
أعلى