fixed sommunication issues

This commit is contained in:
nek0 2024-11-03 16:21:03 +01:00
parent 4716c8d1d0
commit 8dd03d2558
3 changed files with 35 additions and 31 deletions

View file

@ -1,5 +1,4 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module Client.Communication where
@ -48,7 +47,7 @@ sendMessage
-> IO ()
sendMessage msg sock = do
putStrLn $ "sending message: " <> show msg
let msgJson = A.encode msg
let msgJson = ('<' `B8.cons` A.encode msg) `B8.snoc` '>'
msgList = B.unpack $ B.toStrict msgJson
putStrLn $ "sending raw message buffer: " <> show msgList
ptr <- newArray msgList

View file

@ -63,6 +63,9 @@ handleMessage stateContainer readerContainer msg = do
case payload of
ClientQuit -> do
putStrLn $ "client has quit the game: " <> show clientId
currentPlayers <- STM.atomically $ STM.readTMVar (scPlayers stateContainer)
let newPlayers = filter (\p -> playerId p /= clientId) currentPlayers
void $ STM.atomically $ STM.swapTMVar (scPlayers stateContainer) newPlayers
let client = find (\a -> csUUID a == Just clientId) socks
dropClient socketList queueList (csSocket $ fromJust client)
ClientRequestWizard -> do

View file

@ -38,13 +38,11 @@ receiveMessage sockContainer queue = do
sock <- STM.atomically $ STM.readTMVar sockContainer
let maxBufferLength = 4096
putStrLn "read socket container for receiving"
mMsg <- do
ptr <- mallocArray maxBufferLength
putStrLn "receiving data"
eBufferLength <-
try $ recvBuf sock ptr maxBufferLength
putStrLn $ "received raw buffer length of: " <> show eBufferLength
free ptr
bufferLength <- case eBufferLength of
Left (e :: IOException) -> do
-- putStrLn ("Socket vanished, cleaning up after " <> show e)
@ -52,19 +50,23 @@ receiveMessage sockContainer queue = do
pure 0
Right len -> pure len
putStrLn $ "received buffer of length: " <> show bufferLength
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
maybe
(pure ())
rawMsg <- B.pack <$> peekArray bufferLength ptr
free ptr
putStrLn $ "received data: " <> show rawMsg
let msgs =
if B.length rawMsg < 1
then [] :: [B8.ByteString]
else map B8.tail $ init $ B8.split '>' $ B8.fromStrict rawMsg
putStrLn $ "received messages: " <> show msgs
print msgs
mapM_
(\msg -> do
print msg
liftIO $ STM.atomically $ STM.writeTQueue queue msg
-- when (msg == IdRequest) (threadDelay $ 10 ^ 3)
let mJsonMsg = A.decode' msg
maybe
(putStrLn $ "received garbled data: " <> B8.unpack (B8.fromStrict rawMsg))
(\jsonMsg -> do
STM.atomically $ STM.writeTQueue queue jsonMsg
)
mMsg
mJsonMsg
)
msgs