From 03a20112868981493f8ff8f2c72c660f44f5b8e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Domen=20Ko=C5=BEar?= Date: Wed, 27 Dec 2023 15:21:01 +0000 Subject: [PATCH] if socket raises an exception that resource vanished, consider it closed --- src/Network/WebSockets/Stream.hs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Network/WebSockets/Stream.hs b/src/Network/WebSockets/Stream.hs index 06cefe4..d799b7a 100644 --- a/src/Network/WebSockets/Stream.hs +++ b/src/Network/WebSockets/Stream.hs @@ -14,7 +14,7 @@ module Network.WebSockets.Stream import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar, withMVar) -import Control.Exception (SomeException, SomeAsyncException, throwIO, catch, fromException) +import Control.Exception (SomeException, SomeAsyncException, throwIO, catch, try, fromException) import Control.Monad (forM_) import qualified Data.Attoparsec.ByteString as Atto import qualified Data.Binary.Get as BIN @@ -31,6 +31,7 @@ import qualified Network.Socket.ByteString.Lazy as SBL (sendAll) #else import qualified Network.Socket.ByteString as SB (sendAll) #endif +import System.IO.Error (isResourceVanishedError) import Network.WebSockets.Types @@ -116,8 +117,13 @@ makeSocketStream :: S.Socket -> IO Stream makeSocketStream socket = makeStream receive send where receive = do - bs <- SB.recv socket 8192 - return $ if B.null bs then Nothing else Just bs + bs <- try $ SB.recv socket 8192 + case bs of + -- If the resource vanished, the socket was closed + Left e | isResourceVanishedError e -> return Nothing + | otherwise -> throwIO e + Right bs' | B.null bs' -> return Nothing + | otherwise -> return $ Just bs' send Nothing = return () send (Just bs) = do