Can a Blender script stay in memory and listen to a socket? I am considering writing a python script which, once run by the Blender internal interpreter, would stay in memory, listening to a socket and reacting to messages.

As an example I would use this to preview the currently edited object in an external engine, without having to export it to the filesystem then loading it in the engine.

How can I design a plugin to have such a behavior?

Note that this question :


Only targets the "staying in memory / listening to a socket" part with respect to Blender inner workings, not the scene crawling/exporting, messaging details etc.
Does not make reference to the "blender --background" mode of operation. To the contrary I would like this to work in the usual, UI-driven interface.


I am also aware of the Blender Command Port patch, but it does not seem like it has ever been merged (and I would like this to work with a "vanilla" Blender).
Since neither Blender nor Python deal with threading very well.. one option is to use async-IO to handle the network socket, and hook bpy.app.handlers.scene_update_post to have your script called periodically. 

When your handler is called, you would both process async events on the network sockets, and perform whatever operations were requested by the network. Each interation of your handler should run for a relatively short time, or you'll block the UI.