-
Notifications
You must be signed in to change notification settings - Fork 19
/
Server.fs
98 lines (77 loc) · 2.46 KB
/
Server.fs
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
module Server
open System
open System.IO
open System.Threading.Tasks
open Microsoft.AspNetCore
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.Extensions.DependencyInjection
open FSharp.Control.Tasks.V2
open FSharp.Control
open Giraffe
open Reaction.AspNetCore.Middleware
open Shared
open Giraffe.Serialization
let publicPath = Path.GetFullPath "../Client/public"
let port = 8085us
type LetterMsg =
| Set of string
| Get of AsyncReplyChannel<string>
let mailbox =
MailboxProcessor.Start(fun inbox ->
let rec loop letterString =
async {
let! msg = inbox.Receive()
match msg with
| Set letterString ->
return! loop letterString
| Get reply ->
reply.Reply letterString
return! loop letterString
}
loop "Magic Released!"
)
let getInitLetterString () : Task<string> =
Get
|> mailbox.PostAndAsyncReply
|> Async.StartAsTask
let webApp =
route "/api/init" >=>
fun next ctx ->
task {
let! letterString = getInitLetterString()
return! Successful.OK letterString next ctx
}
let stream (connectionId: ConnectionId) (msgs: IAsyncObservable<Msg*ConnectionId>) : IAsyncObservable<Msg*ConnectionId> =
msgs
|> AsyncRx.flatMap(fun (msg,id) ->
match msg with
| Msg.LetterStringChanged letterString ->
mailbox.Post (Set letterString)
| _ -> ()
AsyncRx.single (msg,id))
let configureApp (app : IApplicationBuilder) =
app.UseWebSockets()
.UseStream<Msg>(fun options ->
{ options with
Stream = stream
Encode = Msg.Encode
Decode = Msg.Decode
})
.UseDefaultFiles()
.UseStaticFiles()
.UseGiraffe webApp
let configureServices (services : IServiceCollection) =
services.AddGiraffe() |> ignore
let fableJsonSettings = Newtonsoft.Json.JsonSerializerSettings()
fableJsonSettings.Converters.Add(Fable.JsonConverter())
services.AddSingleton<IJsonSerializer>(NewtonsoftJsonSerializer fableJsonSettings) |> ignore
WebHost
.CreateDefaultBuilder()
.UseWebRoot(publicPath)
.UseContentRoot(publicPath)
.Configure(Action<IApplicationBuilder> configureApp)
.ConfigureServices(configureServices)
.UseUrls("http://0.0.0.0:" + port.ToString() + "/")
.Build()
.Run()