мой первый Haskell сервер :) как это было + haskell sqlite example
перебирал старье на своем компе и наткнулся. воспоминания…
простейший сетевой сервер. печетает построчно то, что приходит в канал.
каждое соединение — в отдельном потоке
import System.IO (hSetBuffering, hGetLine, hPutStrLn,BufferMode(..), Handle, hClose)
import Control.Concurrent (forkIO)
import Control.Monadmain :: IO ()
main = withSocketsDo $ do
— We want to accept multiple connections,
— so we need to accept in a loop
forever $ do
— But once we’ve accepted, we want to go off
— and handle the
— connection in a separate thread
forkIO $ do
msg <- hGetLine handle
putStrLn $ «The client says: « ++ msg
hClose handle
import Database.HDBC{- | Define a function that takes an integer representing the maximum
id value to look up. Will fetch all matching rows from the test database
and print them to the screen in a friendly format. -}
query :: Int -> IO ()
query maxId =
do — Connect to the database
conn <- connectSqlite3 «test1.db»
— Run the query and store the results in r
r <- quickQuery’ conn «SELECT id, desc from test where id <= ? ORDER BY id, desc» [toSql maxId]
— Convert each row into a String
let stringRows = map convRow r
— Print the rows out
mapM_ putStrLn stringRows
— And disconnect from the database
disconnect conn
where convRow :: [SqlValue] -> String
convRow [sqlId, sqlDesc] =
show intid ++ «: « ++ desc
where intid = (fromSql sqlId)::Integer
desc = case fromSql sqlDesc of
Just x -> x
Nothing -> «NULL»
convRow x = fail $ «Unexpected result: « ++ show x
main = do
conn <- connectSqlite3 «test1.db»
run conn «CREATE TABLE test (id INTEGER NOT NULL, desc VARCHAR(80))» []
run conn «INSERT INTO test (id) VALUES (0)» []
commit conn
disconnect conn
——————————————————-