Skip to content

Instantly share code, notes, and snippets.

@andrevdm
Last active March 6, 2024 01:51
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save andrevdm/9560b5e31933391694811bf22e25c312 to your computer and use it in GitHub Desktop.
Save andrevdm/9560b5e31933391694811bf22e25c312 to your computer and use it in GitHub Desktop.
Using websockets with scotty haskell
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();
};
}
{-# 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" :: Text)
threadDelay $ 1 * 1000000
@noxecane
Copy link

Thanks a lot for this

@mudont
Copy link

mudont commented Nov 18, 2020

Exactly the minimal example I was looking for.
Thanks!

@bontaq
Copy link

bontaq commented Apr 4, 2021

very helpful, thanks!

Copy link

ghost commented Jan 17, 2022

https://gist.github.com/andrevdm/9560b5e31933391694811bf22e25c312#file-scotty_websockets-hs-L42 is causing trouble for me.

This could be fixed by adding Text annotation: WS.sendTextData conn $ ("loop data" :: Text)

@andrevdm
Copy link
Author

Thanks @modotte, I've updated.

I'm reasonably sure it worked before, but it has been a while :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment