Close

29.06.2015

мой первый Haskell сервер :) как это было + haskell sqlite example

перебирал старье на своем компе и наткнулся. воспоминания…

простейший сетевой сервер. печетает построчно то, что приходит в канал.

каждое соединение — в отдельном потоке

——————————————————-
import Network (listenOn, withSocketsDo, accept, PortID(..),Socket)
import System.IO (hSetBuffering, hGetLine, hPutStrLn,BufferMode(..), Handle, hClose)
import Control.Concurrent (forkIO)
import Control.Monadmain :: IO ()
main =   withSocketsDo $ do
socket <- listenOn (PortNumber port)—port
   — We want to accept multiple connections,
   — so we need to accept in a loop
forever $ do
(handle, host, portno) <- accept socket
      — But once we’ve accepted, we want to go off
— and handle the

      — connection in a separate thread
forkIO $ do
hSetBuffering handle LineBuffering
msg <- hGetLine handle
putStrLn $ «The client says: « ++ msg
hClose handle
where port = 8080
 ——————————————————-
фууу, еле отформатировал в этом ацком редактре.
BONUS: а вот так можно работать с sqlite
——————————————————-
import Database.HDBC.Sqlite3 (connectSqlite3)
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

——————————————————-

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *