Tcp client in a reliable non-blocking manner

I want to create a TCP client that maintains a reliable connection to a TCP server over WiFi. When WiFi drops the code should retry re-connections to WiFi. When TCP connections are dropped, the TCP client should attempt to reconnect. All this should be in a non-blocking manner (e.g. in a thread). When data is received this data should be made available to the main thread.

I am struggling to find concrete examples or documents on how to achieve this sort of thing. Does anyone know of any recommended approaches, or examples to achieve this sort of thing?

I don’t have a full example, though I will say that it’s possible on the Photon and quite likely impossible on the Electron. The reason is that you can’t call TCPClient from the non-loop thread on the Electron. You can on a Photon.

You can get almost there using state machines and not using threads at all, except for one place: connect() will always be blocking. You can greatly reduce the amount of time it blocks by using an IP address or doing DNS lookups separately and making sure you have Wi-Fi connectivity before trying connect, however. Read and write are not blocking.

If you do go the Photon/thread route it works, but make sure you only call it from one thread. Don’t mix and match between your worker thread and loop thread or software timers because very bad things will eventually happen as there is no thread synchronization in TCPClient.

Ok thanks, I am using a photon so guess I can go the thread route. In other languages passing data between threads causes cross threaded issues and locks and other mechanisms are required to safely do this. Is this the same with the photon? Or can I simply create a public variable in my tcp client wrapper and access that variable from the main thread?

No, you still need to worry about thread synchronization, one of the reasons it’s a pain to implement it using threads.

This is not what you’re looking for; it’s a proof-of-concept sample that implements a non-blocking connect on the Photon. But it still may be helpful because it shows how to create a thread and manage thread synchronization.

I’ll have a look, thanks for the link.