diff options
author | stuebinm | 2021-02-19 00:21:53 +0100 |
---|---|---|
committer | stuebinm | 2021-02-19 00:21:53 +0100 |
commit | 9bea2e88fa7db10756353abcb4c7230af309085a (patch) | |
tree | a96e86529e4951bed2c8c22ac1903dfb69fbe0aa | |
parent | 64dd90ac41f3db7f79b3826c823b971c21a49707 (diff) |
Send JSON instead of bare text
(before, the server just sent "state [n]" on state change, instead of
a properly serialised json value)
-rw-r--r-- | Main.lhs | 9 |
1 files changed, 5 insertions, 4 deletions
@@ -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 |