My suggestion is to have a look at Erel's b4a bridge source code.
About your last question. You can have a 'isConnected' flag. When false (for e.g. inside a astreams_terminated sub), you can enable a timer trying to connect to your server. Eventually, when your server is up again, a connection will be established, so you will set your 'isConnected' flag to true.