2024-11-03 03:40:46 +00:00
|
|
|
{-# LANGUAGE OverloadedStrings #-}
|
2024-05-01 21:52:49 +00:00
|
|
|
module Server.Communication.Receive where
|
|
|
|
|
2024-11-02 22:37:15 +00:00
|
|
|
import Control.Concurrent (threadDelay)
|
|
|
|
|
2024-05-01 21:52:49 +00:00
|
|
|
import qualified Control.Concurrent.STM as STM
|
|
|
|
|
|
|
|
import Control.Exception
|
|
|
|
|
|
|
|
import Control.Monad.IO.Class
|
|
|
|
|
|
|
|
import qualified Data.Aeson as A
|
|
|
|
|
|
|
|
import qualified Data.ByteString as B
|
|
|
|
import qualified Data.ByteString.Lazy.Char8 as B8
|
|
|
|
|
2024-10-31 18:19:13 +00:00
|
|
|
import Foreign.Marshal hiding (void)
|
2024-05-01 21:52:49 +00:00
|
|
|
|
|
|
|
import Network.Socket
|
|
|
|
|
2024-11-02 22:37:15 +00:00
|
|
|
import System.Random
|
|
|
|
|
2024-10-31 18:19:13 +00:00
|
|
|
-- internal imports
|
|
|
|
|
2024-05-01 21:52:49 +00:00
|
|
|
import Library.Types
|
|
|
|
|
|
|
|
import Server.Communication.Send
|
|
|
|
import Server.Types
|
|
|
|
|
|
|
|
-- | receive a 'ClientMessage'
|
|
|
|
receiveMessage
|
2024-10-31 18:19:13 +00:00
|
|
|
:: STM.TMVar Socket
|
2024-05-01 21:52:49 +00:00
|
|
|
-> STM.TQueue ClientMessage
|
|
|
|
-> IO ()
|
2024-11-03 03:40:46 +00:00
|
|
|
receiveMessage sockContainer queue = do
|
2024-11-02 22:37:15 +00:00
|
|
|
randSleep <- randomRIO (1, 1000)
|
|
|
|
threadDelay randSleep
|
2024-11-03 03:40:46 +00:00
|
|
|
sock <- STM.atomically $ STM.readTMVar sockContainer
|
2024-05-01 21:52:49 +00:00
|
|
|
let maxBufferLength = 4096
|
2024-11-03 03:40:46 +00:00
|
|
|
putStrLn "read socket container for receiving"
|
|
|
|
mMsg <- do
|
|
|
|
ptr <- mallocArray maxBufferLength
|
|
|
|
putStrLn "receiving data"
|
|
|
|
eBufferLength <-
|
|
|
|
try $ recvBuf sock ptr maxBufferLength
|
|
|
|
bufferLength <- case eBufferLength of
|
|
|
|
Left (e :: IOException) -> do
|
|
|
|
-- putStrLn ("Socket vanished, cleaning up after " <> show e)
|
|
|
|
-- dropClient clientList sock
|
|
|
|
pure 0
|
|
|
|
Right len -> pure len
|
|
|
|
free ptr
|
|
|
|
msg <- B.pack <$> peekArray bufferLength ptr
|
|
|
|
putStrLn $ "received data: " <> show msg
|
|
|
|
if bufferLength > 0 && msg /= ""
|
|
|
|
then do
|
|
|
|
putStrLn $ "received message: " <> show msg
|
|
|
|
pure (A.decode' $ B8.fromStrict msg :: Maybe ClientMessage)
|
|
|
|
else
|
|
|
|
pure Nothing
|
2024-05-01 21:52:49 +00:00
|
|
|
maybe
|
|
|
|
(pure ())
|
2024-11-03 03:40:46 +00:00
|
|
|
(\msg -> do
|
|
|
|
print msg
|
|
|
|
liftIO $ STM.atomically $ STM.writeTQueue queue msg
|
|
|
|
-- when (msg == IdRequest) (threadDelay $ 10 ^ 3)
|
2024-05-01 21:52:49 +00:00
|
|
|
)
|
2024-11-03 03:40:46 +00:00
|
|
|
mMsg
|