4 people like it.

Websocket request (blocking)

Makes a single Websocket request and waits for the first response

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
open System
open System.Threading
open System.Threading.Tasks
#r "nuget: Websocket.Client, 4.4.43"
#r "nuget: System.Reactive, 4.0.0"
open Websocket.Client

let websocketRequest (reqMsg: string): ResponseMessage =
    let requestTask: Task<ResponseMessage> = 
        task {
            let responseReceivedEvent = new ManualResetEvent(false)
            let mutable msgReceived = None
            let url = new Uri("wss://ws.postman-echo.com/raw");
            use client = new WebsocketClient(url)
            client.ReconnectTimeout <- TimeSpan.FromSeconds(30)
            client.ReconnectionHappened.Subscribe(fun msg ->
                printfn $"Reconnection happened, type: {msg.Type}")
            client.MessageReceived.Subscribe(fun msg ->
                msgReceived <- Some msg
                responseReceivedEvent.Set() |> ignore
            )
            do! client.Start()
            
            Task.Run(fun() -> client.Send(reqMsg)) |> ignore
            responseReceivedEvent.WaitOne(10000) |> ignore
            return Option.get msgReceived
        }
    requestTask.Wait()
    requestTask.Result

let result = websocketRequest "ECHO_MESSAGE"
printfn $"Response text: {result.Text}"
printfn $"Response binary: {result.Binary}"
namespace System
namespace System.Threading
namespace System.Threading.Tasks
namespace Websocket
namespace Websocket.Client
val websocketRequest : reqMsg:string -> ResponseMessage
val reqMsg : string
Multiple items
val string : value:'T -> string

--------------------
type string = String
type ResponseMessage =
  member Binary : byte[]
  member MessageType : WebSocketMessageType
  member Text : string
  member ToString : unit -> string
  static member BinaryMessage : data:byte[] -> ResponseMessage
  static member TextMessage : data:string -> ResponseMessage
val requestTask : Task<ResponseMessage>
Multiple items
type Task =
  new : action:Action -> Task + 7 overloads
  member AsyncState : obj
  member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredTaskAwaitable
  member ContinueWith : continuationAction:Action<Task> -> Task + 19 overloads
  member CreationOptions : TaskCreationOptions
  member Dispose : unit -> unit
  member Exception : AggregateException
  member GetAwaiter : unit -> TaskAwaiter
  member Id : int
  member IsCanceled : bool
  ...

--------------------
type Task<'TResult> =
  inherit Task
  new : function:Func<'TResult> -> Task<'TResult> + 7 overloads
  member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredTaskAwaitable<'TResult>
  member ContinueWith : continuationAction:Action<Task<'TResult>> -> Task + 19 overloads
  member GetAwaiter : unit -> TaskAwaiter<'TResult>
  member Result : 'TResult
  static member Factory : TaskFactory<'TResult>

--------------------
Task(action: Action) : Task
Task(action: Action, cancellationToken: CancellationToken) : Task
Task(action: Action, creationOptions: TaskCreationOptions) : Task
Task(action: Action<obj>, state: obj) : Task
Task(action: Action, cancellationToken: CancellationToken, creationOptions: TaskCreationOptions) : Task
Task(action: Action<obj>, state: obj, cancellationToken: CancellationToken) : Task
Task(action: Action<obj>, state: obj, creationOptions: TaskCreationOptions) : Task
Task(action: Action<obj>, state: obj, cancellationToken: CancellationToken, creationOptions: TaskCreationOptions) : Task

--------------------
Task(function: Func<'TResult>) : Task<'TResult>
Task(function: Func<'TResult>, cancellationToken: CancellationToken) : Task<'TResult>
Task(function: Func<'TResult>, creationOptions: TaskCreationOptions) : Task<'TResult>
Task(function: Func<obj,'TResult>, state: obj) : Task<'TResult>
Task(function: Func<'TResult>, cancellationToken: CancellationToken, creationOptions: TaskCreationOptions) : Task<'TResult>
Task(function: Func<obj,'TResult>, state: obj, cancellationToken: CancellationToken) : Task<'TResult>
Task(function: Func<obj,'TResult>, state: obj, creationOptions: TaskCreationOptions) : Task<'TResult>
Task(function: Func<obj,'TResult>, state: obj, cancellationToken: CancellationToken, creationOptions: TaskCreationOptions) : Task<'TResult>
Multiple items
type ManualResetEvent =
  inherit EventWaitHandle
  new : initialState:bool -> ManualResetEvent

--------------------
ManualResetEvent(initialState: bool) : ManualResetEvent
union case Option.None: Option<'T>
Multiple items
type Uri =
  new : uriString:string -> Uri + 5 overloads
  member AbsolutePath : string
  member AbsoluteUri : string
  member Authority : string
  member DnsSafeHost : string
  member Equals : comparand:obj -> bool
  member Fragment : string
  member GetComponents : components:UriComponents * format:UriFormat -> string
  member GetHashCode : unit -> int
  member GetLeftPart : part:UriPartial -> string
  ...

--------------------
Uri(uriString: string) : Uri
Uri(uriString: string, uriKind: UriKind) : Uri
Uri(baseUri: Uri, relativeUri: string) : Uri
Uri(baseUri: Uri, relativeUri: Uri) : Uri
Multiple items
type WebsocketClient =
  new : url:Uri * ?clientFactory:Func<ClientWebSocket> -> WebsocketClient + 1 overload
  member DisconnectionHappened : IObservable<DisconnectionInfo>
  member Dispose : unit -> unit
  member ErrorReconnectTimeout : Nullable<TimeSpan> with get, set
  member IsReconnectionEnabled : bool with get, set
  member IsRunning : bool with get, set
  member IsStarted : bool with get, set
  member IsTextMessageConversionEnabled : bool with get, set
  member MessageEncoding : Encoding with get, set
  member MessageReceived : IObservable<ResponseMessage>
  ...

--------------------
WebsocketClient(url: Uri,?clientFactory: Func<Net.WebSockets.ClientWebSocket>) : WebsocketClient
WebsocketClient(url: Uri, connectionFactory: Func<Uri,CancellationToken,Task<Net.WebSockets.WebSocket>>) : WebsocketClient
Multiple items
type TimeSpan =
  struct
    new : ticks:int64 -> TimeSpan + 3 overloads
    member Add : ts:TimeSpan -> TimeSpan
    member CompareTo : value:obj -> int + 1 overload
    member Days : int
    member Divide : divisor:float -> TimeSpan + 1 overload
    member Duration : unit -> TimeSpan
    member Equals : value:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member Hours : int
    member Milliseconds : int
    ...
  end

--------------------
TimeSpan ()
TimeSpan(ticks: int64) : TimeSpan
TimeSpan(hours: int, minutes: int, seconds: int) : TimeSpan
TimeSpan(days: int, hours: int, minutes: int, seconds: int) : TimeSpan
TimeSpan(days: int, hours: int, minutes: int, seconds: int, milliseconds: int) : TimeSpan
TimeSpan.FromSeconds(value: float) : TimeSpan
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Raw view Test code New version

More information

Link:http://fssnip.net/88W
Posted:1 year ago
Author:Fave Oled
Tags: websocket , websocket .net