gpt4 book ai didi

f# - 观察模式下的 Suave(开发期间)

转载 作者:行者123 更新时间:2023-12-04 06:34:10 25 4
gpt4 key购买 nike

我正在处理 Suave 1.0 + Angular 2.0 sample app在监视模式下启动Suave服务器非常有趣,因此服务器监视根文件夹和子文件夹中的文件(js,css,html)并自动发送refresh当任何文件发生更改时,我的应用程序对所有打开的浏览器选项卡的命令。
lite-server来自 Angular 2 5min Quckstark可以做到这一点,而且非常方便。

我认为大部分 watch 都可以在latest Steffen Forkmann's post中找到。但是不是很干净怎么发refresh到打开的浏览器选项卡。

请提供类似实现的完整代码 Suave .

最佳答案

Suave的代码服务器应该与此类似

#r "packages/Suave/lib/net40/suave.dll"
#r "packages/FAKE/tools/FakeLib.dll"

open Fake
open Suave
open Suave.Operators
open Suave.Sockets.Control
open Suave.WebSocket
open Suave.Utils
open Suave.Files
open Suave.RequestErrors
open Suave.Filters
open System
open System.Net


let port =
let rec findPort port =
let portIsTaken =
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()
|> Seq.exists (fun x -> x.Port = int(port))
if portIsTaken then findPort (port + 1us) else port
findPort 8083us

let logger = Logging.Loggers.ConsoleWindowLogger Logging.LogLevel.Verbose

let refreshEvent = new Event<_>()

let handleWatcherEvents (events:FileChange seq) =
for e in events do
let fi = fileInfo e.FullPath
traceImportant <| sprintf "%s was changed." fi.Name
refreshEvent.Trigger()

let socketHandler (webSocket : WebSocket) =
fun cx -> socket {
while true do
let! refreshed =
Control.Async.AwaitEvent(refreshEvent.Publish)
|> Suave.Sockets.SocketOp.ofAsync
do! webSocket.send Text (ASCII.bytes "refreshed") true
}

let cfg =
{ defaultConfig with
homeFolder = Some (__SOURCE_DIRECTORY__)
bindings =
[ HttpBinding.mk HTTP IPAddress.Loopback port ]
listenTimeout = TimeSpan.FromMilliseconds 3000. }

let app : WebPart =
choose [
Filters.log logger logFormat >=> never
Filters.path "/websocket" >=> handShake socketHandler
Filters.GET >=> Filters.path "/" >=> file "index.html"
Writers.setHeader "Cache-Control" "no-cache, no-store, must-revalidate"
>=> Writers.setHeader "Pragma" "no-cache"
>=> Writers.setHeader "Expires" "0"
>=> browseHome
NOT_FOUND "Found no handlers."
]


let watcher =
!! ("app/*.js")
++ ("*.html")
|> WatchChanges handleWatcherEvents

try
System.Diagnostics.Process.Start(sprintf "http://localhost:%d/index.html" port) |> ignore
startWebServer cfg app
finally
watcher.Dispose()

所以我们设置观察者来处理 js 中的变化(由 TypeScript 生成)和 html文件并发送 refresh命令到客户端,但同时我们需要将以下代码添加到 head index.html的部分处理 refresh在客户端
<!-- 3. Listen on refresh events from the server -->
<script language="javascript" type="text/javascript">
function init()
{
websocket = new WebSocket("ws://"+window.location.host+"/websocket");
websocket.onmessage = function(evt) { location.reload(); };
}
window.addEventListener("load", init, false);
</script>

您可以找到完整的演示应用程序 here

关于f# - 观察模式下的 Suave(开发期间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34603913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com