This is a simple proof-of-concept web app that demonstrates the use of websockets with the Haskell Spock library.
- Spock, a lightweight Haskell web framework
- websockets, a sensible and clean way to write WebSocket-capable servers in Haskell
The source code contains a simple demo that streams the sequence of numbers that are displayed in the browser with a visual gimmick.
The key thing to realize is that websocketsOr produces a Middleware that can be supplied to runSpock.
Middleware is a component that sits between the server and application:
type Middleware = Application -> Application -- defined in Network.Wai
and websocketsOr
can produce one
wsMiddleware :: Middleware
wsMiddleware = websocketsOr defaultConnectionOptions wsApp
where ...
The ServerApp
is
wsApp :: ServerApp
wsApp pendingConn = do
conn <- acceptRequest pendingConn
counter conn 1
The counter
is an endless recursion (loop) that just counts up:
counter :: Connection -> Int -> IO ()
counter conn i = do
threadDelay 50000 -- 50ms
sendTextData conn (T.pack $ show i)
counter conn (i + 1)
This is tied in with the Spock app by defining the appMiddlewares
appMiddlewares = do
middleware (staticPolicy $ noDots >-> addBase "static")
middleware wsMiddleware
Now all is ready to start the server:
runSpock 8080 (spock spockConfig (appMiddlewares >> app))