I'm trying to listen for UDP Datagrams for just 3 seconds in Haskell. I wrote some code but I'm not sure why it's not working. I set the timeout to 3 seconds, but it just waits forever and doesn't block
import Control.Concurrent as CC (forkIO, threadDelay, killThread)
import qualified Data.ByteString.Char8 as C
import Network.Socket
import Network.Socket.ByteString as B
import Data.IORef
import Control.Monad (forever)
import System.Timeout
receiveDatagram = do
ack <- newIORef (0 :: Int)
addrinfos <- getAddrInfo Nothing (Just "127.0.0.1") (Just "7001")
let serveraddr = head addrinfos
sock <- socket (addrFamily serveraddr) Datagram defaultProtocol
bind sock (addrAddress serveraddr)
print "starting"
tmp <- timeout 3000000 (do
(msg, addr) <- B.recvFrom sock 1024
close sock
writeIORef ack 1
print msg
)
case tmp of
Nothing -> close sock
_ -> print "something else"
print "timeout done"
The documentation for timeout states:
Standard I/O functions like hGetBuf, hPutBuf, Network.Socket.accept, or hWaitForInput appear to be blocking, but they really don't because the runtime system uses scheduling mechanisms like select(2) to perform asynchronous I/O, so it is possible to interrupt standard socket I/O or file I/O using this combinator.