Last active
July 12, 2017 07:52
-
-
Save whitetigle/57ccf0dbee69e48749fc15e17f631f6f to your computer and use it in GitHub Desktop.
sample code for Suave websocket
This file contains hidden or 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
| module ServerSocket | |
| open Suave.Sockets | |
| open Suave.Sockets.Control | |
| open Suave.WebSocket | |
| open System.Threading | |
| let broadCast = new Event<byte[]>() | |
| let broadCasted = broadCast.Publish | |
| let handleWebsocketConnection (ws: WebSocket) = | |
| let notifyLoop = async { | |
| while true do | |
| let! msg = Async.AwaitEvent broadCasted | |
| let byteResponse = msg |> ByteSegment | |
| let! a = ws.send Text byteResponse true | |
| return () | |
| } | |
| let cts = new CancellationTokenSource() | |
| Async.Start(notifyLoop, cts.Token) | |
| fun context -> | |
| socket { | |
| let loop = ref true | |
| while !loop do | |
| let! m = ws.read() | |
| match m with | |
| | Text,data,true -> broadCast.Trigger(data) | |
| | Ping,_,_ -> () | |
| | Close,_,_ -> loop := false | |
| | _ -> () | |
| } | |
| let sendMessage (message:string) = | |
| let byteResponse = message |> System.Text.Encoding.ASCII.GetBytes | |
| broadCast.Trigger byteResponse | |
| (* | |
| sample use : | |
| ServerSocket.sendMessage "my string" | |
| *) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment