Introduce channel for communication with main thread
Add basic support for sending messages
Massive refactoring
Refactoring: use ValidTransportState in mainloop function.