wizard-wipeout/src-client/Client/Communication.hs

86 lines
2 KiB
Haskell
Raw Normal View History

2023-12-10 19:12:53 +00:00
{-# LANGUAGE LambdaCase #-}
module Client.Communication where
2023-12-12 10:21:25 +00:00
import Control.Concurrent (threadDelay)
import qualified Control.Concurrent.STM as STM
2023-12-11 06:07:09 +00:00
import Control.Monad (void)
2023-12-12 08:47:50 +00:00
import Control.Monad.RWS
2023-12-10 19:12:53 +00:00
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy.Char8 as B8
import Data.Maybe (fromJust)
2023-12-11 06:07:09 +00:00
import qualified Data.Vector.Storable as VS
2023-12-11 06:07:09 +00:00
import Foreign hiding (void)
import Network.Socket
2023-12-12 08:47:50 +00:00
import System.Posix.Signals
2023-12-10 19:12:53 +00:00
-- internal imports
import Library.Types
2023-12-12 08:47:50 +00:00
import Client.Types
2023-12-10 19:12:53 +00:00
connectSocket
:: FilePath
2023-12-10 19:12:53 +00:00
-> IO Socket
connectSocket path = do
sock <- socket AF_UNIX Stream defaultProtocol
setSocketOption sock KeepAlive 1
connect sock (SockAddrUnix path)
2023-12-10 19:12:53 +00:00
pure sock
-- | Sends a specified message through given socket to the server
sendMessage
2023-12-11 08:49:24 +00:00
:: ClientMessage
2023-12-10 19:12:53 +00:00
-> Socket
-> IO ()
sendMessage msg sock = do
let msgJson = A.encode msg
2023-12-11 06:07:09 +00:00
msgVector = VS.fromList $ B.unpack $ B.toStrict msgJson
VS.unsafeWith
msgVector
(\ptr -> void $ sendBuf sock ptr (VS.length msgVector))
2023-12-10 19:12:53 +00:00
receiveMessage
:: Socket
-> STM.TQueue ServerMessage
-> IO ()
receiveMessage sock queue = do
2023-12-11 06:07:09 +00:00
let maxBufferLength = 4096
ptr <- mallocArray maxBufferLength
bufferLength <- recvBuf sock ptr maxBufferLength
msg <- B.pack <$> peekArray bufferLength ptr
let mJsonMsg = A.decode' $ B8.fromStrict msg
maybe
2023-12-12 01:53:05 +00:00
(putStrLn $ "received garbled data: " <> B8.unpack (B8.fromStrict msg))
(STM.atomically . STM.writeTQueue queue)
2023-12-11 06:07:09 +00:00
mJsonMsg
2023-12-12 08:47:50 +00:00
-- | Function that installs a handler on SIGINT to terminate game
terminateGameOnSigint
:: Game ()
terminateGameOnSigint = do
sock <- asks rcSocket
clientId <- asks rcClientUUID
clientState <- gets scClientState
void $ liftIO $ installHandler
keyboardSignal
(CatchOnce $ do
2023-12-12 10:21:25 +00:00
currentState <- STM.atomically $ STM.readTMVar clientState
2023-12-12 08:47:50 +00:00
threadDelay (10 ^ 6)
2023-12-12 10:21:25 +00:00
sendMessage (ClientMessage clientId ClientQuit) sock
2023-12-12 08:47:50 +00:00
close sock
-- Raise SIGINT again so it does not get blocked
raiseSignal keyboardSignal
)
Nothing