Skip to content

Instantly share code, notes, and snippets.

@yomimono
Created March 10, 2014 23:03
Show Gist options
  • Save yomimono/9476285 to your computer and use it in GitHub Desktop.
Save yomimono/9476285 to your computer and use it in GitHub Desktop.
fortune server in haskell
import Control.Concurrent (forkIO)
import Control.Monad (forever)
import Network
import System.IO
import System.Random
rand :: Int -> IO Int
rand p = getStdRandom (randomR (0, p))
fortune :: [String] -> (Handle, HostName, PortNumber) -> IO ()
fortune fortunes (rHandle, rHostname, rPort) = do
fortuneIndex <- rand (length fortunes - 1)
hPutStrLn rHandle (fortunes !! fortuneIndex)
hClose rHandle
main = do
fortuneFile <- readFile "fortune.txt"
listener <- listenOn (PortNumber 12345)
forever $ do
(rHandle, rHostname, rPort) <- accept listener
forkIO (fortune (lines fortuneFile) (rHandle, rHostname, rPort))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment