Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume websockets

Tags:

f#

fable-f#

How do I consume data from, and push data to a websocket using Fable? I found this github issue which suggests that it can be done, but cannot find any documentation or examples of how to achieve this.

like image 280
Lawrence Avatar asked Oct 24 '16 16:10

Lawrence


1 Answers

For anyone who finds this question later via Google, here's the response that @Lawrence received from Maxime Mangel when he asked this question on Gitter:

Hello @lawrencetaylor you can find here an old sample using websockets with FableArch. Don't consider the code 100% correct because it's from an older version of fable-arch.

This code should however show you how to use websockets with fable-arch logic. https://github.com/fable-compiler/fable-arch/commit/abe432881c701d2df65e864476bfa12cf7cf9343

First you create the websocket here.

Here you can see how to send a message over a websocket.

And here how to listen on a websocket.

I've copied the code he mentioned below, so that anyone who finds this question later will be able to read it without having to follow those links. Credit for the code below goes to Maxime Mangel, not me.

Websocket creation

let webSocket =
    WebSocket.Create("wss://echo.websocket.org")

Sending a message over a websocket

webSocket.send("Hello, socket!")

Listening on a websocket

let webSocketProducer push =
  webSocket.addEventListener_message(
    Func<_,_>(fun e ->
      push(ReceivedEcho (unbox e.data))
      null
  )
)

createApp Model.initial view update
|> withProducer webSocketProducer
|> start renderer

NOTE: ReceivedEcho in the above code is one of the cases of the Action discriminated union, which is a standard pattern in the fable-arch way of doing things. And withProducer is a function from fable-arch. See http://fable.io/fable-arch/samples/clock/index.html for a simple example of how to use withProducer.

like image 68
rmunn Avatar answered Oct 25 '22 09:10

rmunn