Safe Haskell | Safe-Infered |
---|
Use Lazy ByteString
s of JSON to send and receive messages.
For this module, a message is prefixed by a
64-bit little-endian signed integer, indicating the length in bytes
of the remaining message, which is encoded in JSON format.
- receive :: (MonadIO io, FromJSON j) => Handle -> io (Maybe j)
- (!) :: (CanSendJson h, MonadIO io) => ToJSON j => h -> j -> io ()
- send :: MonadIO io => ToJSON j => Handle -> j -> io ()
- broadcast :: MonadIO io => (ToJSON j, Foldable f) => f Handle -> j -> io ()
- deriveJson :: (String -> String) -> Name -> Q [Dec]
Receiving
receive :: (MonadIO io, FromJSON j) => Handle -> io (Maybe j)Source
Receive a JSON message from a Handle
.
Unlike Text
and ByteString
, the result
of this MonadIO action is wrapped in a Maybe
.
Nothing
means that the data received
could not be parsed from JSON to the correct data type.
It is up to you to decide whether or not to explicitly handle
the Nothing
case.
Notice that this action is polymorphic in its return type. Type annotations are usually unnecessary, since type inference can usually determine the correct target type. Example usage:
do Just m <- receive h case m of Foo x y -> handleFoo x y Bar z -> handleBar z
Here m
is inferred to have whatever type Foo
and Bar
belong to.
This example code assumes that the JSON parse will succeed.
The fail
function will be invoked for the Monad you are working
in if such a pattern match fails.
Sending
(!) :: (CanSendJson h, MonadIO io) => ToJSON j => h -> j -> io ()Source
The staple for sending a message.
!
is typeclassed so that you can
send
or broadcast
using the same simple syntax.
The CanSendJson
typeclass is not exposed.
Instances of CanSendJson include Handle
and Traversable t => t Handle
.
!
produces an IO
action lifted into any MonadIO
,
so can be used without the extra cruft of liftIO
for most monad stacks. !
is declared as infix 2
.
Usage:
destination ! someData
Anything that is an instance of ToJSON
can be used
on the right-hand side of !
.
send :: MonadIO io => ToJSON j => Handle -> j -> io ()Source
Send a JSON message to exactly one Handle
.
broadcast :: MonadIO io => (ToJSON j, Foldable f) => f Handle -> j -> io ()Source
Broadcast a JSON message to multiple Handle
s.
JSON
deriveJson :: (String -> String) -> Name -> Q [Dec]Source
Derives ToJSON
and FromJSON
instances
for your data types. These are necessary in order to
use the functions this module provides with your
custom data types.
Usage:
{-# LANGUAGE TemplateHaskell #-} data Foo = Bar | Baz { quux :: Int } $(deriveJson id ''Foo)
Alteratively, you could write your own instances.