/spock-websocket

Simple little web app to show how easy it is to use websockets with Haskell Spock.

Primary LanguageHaskellBSD 3-Clause "New" or "Revised" LicenseBSD-3-Clause

Spock-Websockets

This is a simple proof-of-concept web app that demonstrates the use of websockets with the Haskell Spock library.

Main libraries used

  • Spock, a lightweight Haskell web framework
  • websockets, a sensible and clean way to write WebSocket-capable servers in Haskell

Demo

The source code contains a simple demo that streams the sequence of numbers that are displayed in the browser with a visual gimmick.

animated gif

How it works

The key thing to realize is that websocketsOr produces a Middleware that can be supplied to runSpock.

Middleware

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

Counter

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

Start Spock

Now all is ready to start the server:

runSpock 8080 (spock spockConfig (appMiddlewares >> app))