From 9bea2e88fa7db10756353abcb4c7230af309085a Mon Sep 17 00:00:00 2001 From: stuebinm Date: Fri, 19 Feb 2021 00:21:53 +0100 Subject: Send JSON instead of bare text (before, the server just sent "state [n]" on state change, instead of a properly serialised json value) --- Main.lhs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Main.lhs b/Main.lhs index 3799fbe..c05c2ab 100644 --- a/Main.lhs +++ b/Main.lhs @@ -63,6 +63,7 @@ are pretty boring: > data State = State { state :: Int } deriving (Show, Generic) > instance FromJSON Join > instance FromJSON State +> instance ToJSON State Join is sent after a connection is established to indicate which room should be joined, State to indicate a state change @@ -124,7 +125,7 @@ to the usual message handling loop, which just needs the room's state, not the server's global state: > putStrLn $ show i <> " joined room " <> (show $ room join) -> WS.sendTextData conn (T.pack $ "state " <> show n) +> WS.sendTextData conn $ encode State { state = n } > talk (i, conn) roomstate Only one thing is still left to do, which is to define the `insertClient` @@ -163,7 +164,7 @@ it did drop them). > Left err -> putStrLn $ "json malformed" <> err > Right new -> do > peers <- modifyMVar roomstate $ \(cs,n) -> return ((cs, state new), cs) -> broadcast ("state " <> (T.pack $ show $ state new)) peers +> broadcast (encode $ State { state = state new }) peers > where > disconnect i = do > modifyMVar_ roomstate (\room -> return $ removeClient i room) @@ -176,9 +177,9 @@ Note that this is a linked list (i.e. may be slow and cause some cache misses while iterating), but it's probably going to be fine unless there's a couple thousand clients in a room. -> broadcast :: Text -> [Client] -> IO () +> broadcast :: LB.ByteString -> [Client] -> IO () > broadcast message cs = do -> --T.putStrLn message -- log messages +> LB.putStrLn message -- log messages > forM_ cs $ \(_,conn) -> WS.sendTextData conn message -- cgit v1.2.3