Skip to content

Instantly share code, notes, and snippets.

@aggieben
Created May 27, 2017 04:21
Show Gist options
  • Save aggieben/693751844eeccfca52950206bd033d06 to your computer and use it in GitHub Desktop.
Save aggieben/693751844eeccfca52950206bd033d06 to your computer and use it in GitHub Desktop.
module WebSocketClient
open System
open System.Net.WebSockets
open System.Text
open System.Threading
open Newtonsoft.Json
[<EntryPoint>]
let main argv =
use cts = new CancellationTokenSource()
use socket = new ClientWebSocket()
Async.AwaitTask(socket.ConnectAsync(Uri("wss://mysocketurl"), cts.Token)) |> Async.RunSynchronously
Logger.log.Information("Connected to socket.")
let buffer : byte array = Array.zeroCreate 1024
let segment = ArraySegment(buffer)
let rec loop() =
async {
Logger.log.Verbose("waiting for message. Socket state: {0}", socket.State)
let! result = Async.AwaitTask (socket.ReceiveAsync(segment, cts.Token))
Logger.log.Debug("result: {result}", result)
let msg = Encoding.UTF8.GetString(buffer)
Logger.log.Debug("received message:\n{msg}", msg)
Array.fill buffer 0 buffer.Length 0uy
return! loop()
}
let subscribeMsg = Encoding.UTF8.GetBytes @"{ ""type"": ""subscribe"" }"
Async.Start (Async.AwaitTask (socket.SendAsync(ArraySegment(subscribeMsg), WebSocketMessageType.Text, true, cts.Token)))
loop() |> Async.RunSynchronously
0 // return an integer exit code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment