Automatically reconnect a Haskell network connection on an idiomatic path

I worked my way through Don Stewart Roll up my own IRC bot tutorial and I play with some extensions to it. My current code is essentially the same as "Monadic, position-driven, bug-managing bot in all its glory"; it is too long to insert here unless someone asks for it.

As a Comcast subscriber, it is especially important that the bot can reconnect after periods of poor communication. My approach is to simply request PING requests from the server, and if it goes without seeing PING for a certain amount of time, try reconnecting.

So far, the best I've found is to wrap hGetLine in a listen loop using System.Timeout.timeout . However, this requires a custom exception to be defined so that catch in main can call main again, rather than return () . It also seems pretty fragile to specify a timeout value for each individual hGetLine .

Is there a better solution, perhaps something that wraps IO a like bracket and catch so that the entire main object can handle network timeouts without the overhead of a new exception type?

+7
source share
1 answer

How to start a separate thread that does all the reading and writing and takes care of re-connecting the handle?

Something like that

  input :: Chan Char output :: Chan Char putChar c = writeChan output c keepAlive = forever $ do h <- connectToServer catch (forever $ do c <- readChan output; timeout 4000 (hPutChar hc); return ()) (\_ -> return ()) 

The idea is to encapsulate all the difficulties by periodically reconnecting to a separate stream.

+1
source

All Articles