如何在以下代码示例中向所有 websocket 客户端广播事件:
let echo (ws : WebSocket) =
fun cx -> socket {
let loop = ref true
while !loop do
let! msg = ws.read();
match msg with
| (Text, data, true) ->
let str = UTF8.toString data
printfn "****** Received: %s" str
do! ws.send Text data true
| (Ping, _, _) ->
do! ws.send Pong [||] true
| (Close, _, _) ->
do! ws.send Close [||] true
loop := false
| _ -> ()
}
let start home port =
let config =
{ defaultConfig with
logger = Logging.Loggers.saneDefaultsFor Logging.LogLevel.Verbose
bindings = [ (if port |> String.IsNullOrEmpty then
HttpBinding.mkSimple HTTP "127.0.0.1" 3000
else HttpBinding.mkSimple HTTP "0.0.0.0" (int32 port)) ]
homeFolder = home |> Some }
let app =
choose
[
path "/echo" >=> handShake echo
NOT_FOUND "Sorry there is nothing there"
]
startWebServer config app
所以,基本上,我希望能够向服务器 websocket 发送消息,并将该消息回显到所有当前的 websocket 客户端。用例是我有一个文件观察器,它向服务器 websocket 发送消息,浏览器中的 websocket 客户端将在收到消息时刷新浏览器。
我想我需要保留一份客户名单,但我不确定使用 suave 的最佳方法是什么。
例如,使用 express 这很简单:
(function () {
var debug = require('debug')('app:server');
var app = require('express')();
var ws = require('express-ws')(app);
var PORT = process.env.PORT || 1337;
// enable cors
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
return next();
});
app.get('/', function (req, res, next) {
debug('get route');
res.send('hello');
res.end();
});
app.ws('/', function (ws, req) {
ws.on('message', function (msg) {
debug('websocket message', msg);
});
});
app.listen(PORT);
debug('watch server started on port: ' + PORT);
/// Broadcast the reload event to all clients.
exports.reload = function () {
ws.getWss().clients.forEach(function (client) {
debug('*** broadcast reload message');
client.send('reload');
});
};
}());