on master help sign in
Add code example in the TCP module
commita96d1643408d8a495c27674df40ad408abf482f9 authorHarendra Kumar <harendra@composewell.com> dateThu 7 Dec 2023, 11:07 (3 years ago) parentdeb8b34
2 files changed+31−4
src/Streamly/Network/Inet/TCP.hs+28 src/Streamly/Network/Socket.hs+3−4
src/Streamly/Network/Inet/TCP.hs+28
@@ -11,6 +11,34 @@
1111--
1212-- >>> import qualified Streamly.Network.Inet.TCP as TCP
1313--
14+-- = Examples
15+--
16+-- Following is a short example of a concurrent echo server.
17+--
18+-- >>> import Control.Monad.Catch (finally)
19+-- >>> import Data.Function ((&))
20+-- >>> import Network.Socket (Socket)
21+-- >>>
22+-- >>> import qualified Network.Socket as Net
23+-- >>> import qualified Streamly.Data.Fold as Fold
24+-- >>> import qualified Streamly.Data.Stream.Prelude as Stream
25+-- >>> import qualified Streamly.Network.Inet.TCP as TCP
26+-- >>> import qualified Streamly.Network.Socket as Socket
27+-- >>>
28+-- >>> :{
29+-- main :: IO ()
30+-- main =
31+-- TCP.accept 8091 -- Stream IO Socket
32+-- & Stream.parMapM id (handleExceptions echo) -- Stream IO ()
33+-- & Stream.fold Fold.drain -- IO ()
34+-- where
35+-- echo :: Socket -> IO ()
36+-- echo sk =
37+-- Socket.readChunksWith 32768 sk -- Stream IO (Array Word8)
38+-- & Stream.fold (Socket.writeChunks sk) -- IO ()
39+-- handleExceptions :: (Socket -> IO ()) -> Socket -> IO ()
40+-- handleExceptions f sk = finally (f sk) (Net.close sk)
41+-- :}
1442
1543module Streamly.Network.Inet.TCP
1644 (
src/Streamly/Network/Socket.hs+3−4
@@ -10,13 +10,13 @@
1010-- This module provides socket based streaming APIs to to receive connections
1111-- from remote hosts, and to read and write from and to network sockets.
1212--
13−-- For basic socket types and operations please consult the @Network.Socket@
13+-- For basic socket types and non-streaming operations please consult the @Network.Socket@
1414-- module of the <http://hackage.haskell.org/package/network network> package.
1515--
1616-- = Examples
1717--
18−-- To write a server, use the 'acceptor' unfold to start listening for
19−-- connections from clients. 'acceptor' generates a stream of connected
18+-- To write a server, use the 'accept' stream to start listening for
19+-- connections from clients. 'accept' generates a stream of connected
2020-- sockets. We can map an effectful action on this socket stream to handle the
2121-- connections. The action would typically use socket reading and writing
2222-- operations to communicate with the remote host. We can read/write a stream
@@ -33,7 +33,6 @@
3333-- >>> import Streamly.Network.Socket (SockSpec(..))
3434-- >>>
3535-- >>> import qualified Streamly.Data.Fold as Fold
36−-- >>> import qualified Streamly.Data.Stream as Stream
3736-- >>> import qualified Streamly.Data.Stream.Prelude as Stream
3837-- >>> import qualified Streamly.Network.Socket as Socket
3938-- >>>