on master help sign in
update client/server examples
commit68690bb4ed584fd18d2642eecd23a06e29323554 authorHarendra Kumar <harendra.kumar@gmail.com> dateWed 29 May 2019, 09:59 (7 years ago) parentd50214a
2 files changed+39−14
examples/FileSinkServer.hs+24−9 examples/FromFileClient.hs+15−5
examples/FileSinkServer.hs+24−9
@@ -1,4 +1,14 @@
1−-- A concurrent TCP server that prints everything it receives to stdout.
1+-- A concurrent TCP server that:
2+--
3+-- * receives connections from clients
4+-- * splits the incoming data into lines
5+-- * lines from concurrent connections are merged into a single srteam
6+-- * writes the line stream to an output file
7+
8+import Control.Monad.IO.Class (liftIO)
9+import Data.Char (ord, chr)
10+import System.IO (openFile, IOMode(..), hClose, hPutStrLn)
11+import System.Environment (getArgs)
212
313import Streamly
414import qualified Streamly.Fold as FL
@@ -8,15 +18,20 @@ import qualified Network.Socket as NS
818import qualified Streamly.Prelude as S
919
1020main :: IO ()
11−main = S.drain
12− $ parallely $ S.mapM (withSocket recv)
13− $ serially $ fmap fst (NS.recvConnectionsOn 8090)
21+main = do
22+ h <- openOutput
23+ S.mapM_ (hPutLines h)
24+ $ S.concatMapBy parallel (withSocket recv)
25+ $ fmap fst (NS.recvConnectionsOn 8090)
26+ hClose h
1427
1528 where
1629
17− withSocket f sk = f sk >> NS.close sk
30+ openOutput = fmap head getArgs >>= \file -> openFile file AppendMode
31+
32+ withSocket f sk = S.finally (liftIO (NS.close sk)) (f sk)
33+ hPutLines h = hPutStrLn h . map (chr . fromIntegral) . A.toList
34+ ord' = (fromIntegral . ord)
1835 recv =
19− S.mapM_ print
20− . FL.sessionsOf 3 FL.sum
21− . S.map A.length
22− . NS.readArrays
36+ FL.splitSuffixBy (== ord' '\n') (A.toArrayN 1024)
37+ . NS.read
examples/FromFileClient.hs+15−5
@@ -1,19 +1,29 @@
1−-- A TCP client that reads from stdin and sends to a server
1+-- A TCP client that does the following:
2+-- * Reads multiple filenames passed on the command line
3+-- * Opens as many concurrent connections to the server
4+-- * Sends all the files concurrently to the server
25
36import Network.Socket
4−import System.IO (stdin)
7+import System.IO (openFile, IOMode(..), hClose)
8+import System.Environment (getArgs)
59
10+import Streamly
611import qualified Streamly.Prelude as S
712import qualified Streamly.FileSystem.File as File
813import qualified Streamly.Network.Socket as NS
914
1015main :: IO ()
11−main = do
12− openConnection >>= \sk ->
13− S.drain $ NS.writeArrays sk $ File.readArrays stdin
16+main = getArgs >>= S.drain . parallely . S.mapM sendFile . S.fromList
1417
1518 where
1619
20+ sendFile file = do
21+ h <- openFile file ReadMode
22+ openConnection >>= \sk -> do
23+ S.drain $ NS.writeArrays sk $ File.readArrays h
24+ close sk
25+ hClose h
26+
1727 openConnection = do
1828 sock <- socket AF_INET Stream defaultProtocol
1929 connect sock $ SockAddrInet 8090 (tupleToHostAddress (127,0,0,1))