-
-
Save voidus/0e0f6d2b3df4dc3cc2a32d8d36c8aab5 to your computer and use it in GitHub Desktop.
Using websockets with scotty haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function webSocketTest() | |
{ | |
var ws = new WebSocket("ws://localhost:80"); | |
ws.onopen = () => { | |
ws.send("initial from js"); | |
}; | |
ws.onmessage = evt => { | |
var m = evt.data; | |
console.log( m ); | |
}; | |
ws.onclose = function() { | |
alert("ws closed"); | |
}; | |
window.onbeforeunload = evt => { | |
socket.close(); | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE NoImplicitPrelude #-} | |
{-# LANGUAGE ScopedTypeVariables #-} | |
{-# LANGUAGE OverloadedStrings #-} | |
module Main where | |
import Protolude | |
import qualified Web.Scotty as Sc | |
import qualified Data.Text as Txt | |
import qualified Network.Wai.Middleware.Gzip as Sc | |
import qualified Network.Wai.Handler.WebSockets as WaiWs | |
import qualified Network.WebSockets as WS | |
import qualified Network.Wai as Wai | |
import qualified Network.Wai.Handler.Warp as Warp | |
main :: IO () | |
main = do | |
let port = 80 | |
let settings = Warp.setPort port Warp.defaultSettings | |
sapp <- scottyApp | |
Warp.runSettings settings $ WaiWs.websocketsOr WS.defaultConnectionOptions wsapp sapp | |
scottyApp :: IO Wai.Application | |
scottyApp = | |
Sc.scottyApp $ do | |
Sc.middleware $ Sc.gzip $ Sc.def { Sc.gzipFiles = Sc.GzipCompress } | |
--Sc.middleware S.logStdoutDev | |
Sc.get "/" $ | |
Sc.file "index.html" | |
wsapp :: WS.ServerApp | |
wsapp pending = do | |
putText "ws connected" | |
conn <- WS.acceptRequest pending | |
WS.forkPingThread conn 30 | |
(msg :: Text) <- WS.receiveData conn | |
WS.sendTextData conn $ ("initial> " :: Text) <> msg | |
forever $ do | |
WS.sendTextData conn $ "loop data" | |
threadDelay $ 1 * 1000000 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment