mirror of
https://github.com/labring/laf.git
synced 2026-01-18 16:03:17 +00:00
* doc: update package-manage.md * doc: add cloudfunction docs * doc: add use-env doc * doc: upload image file into project directory --------- Co-authored-by: sulnong <bytepay@bytepayment.com>
1.7 KiB
1.7 KiB
| title |
|---|
| 云函数处理 WebSocket 长连接 |
{{ $frontmatter.title }}
WebSocket 触发器
提示:在使用 WebSocket 之前一定要建立触发器,详见触发器章节
当应用收到 WebSocket 消息时,会触发以下云函数事件,开发者为任一云函数配置以下触发器,即可处理 WebSocket 消息
WebSocket:connection有新 WebSocket 连接建立时触发,通过ctx.socket获取连接WebSocket:message接收 WebSocket 消息时触发,通过ctx.params获取消息数据WebSocket:close有 WebSocket 连接关闭时触发WebSocket:error有 WebSocket 连接出错时触发
以下是云函数中处理 WebSocket 示例:
exports.main = async function (ctx) {
if (ctx.method === "WebSocket:connection") {
ctx.socket.send("hi connection succeed");
}
if (ctx.method === "WebSocket:message") {
const { data } = ctx.params;
console.log(data.toString());
ctx.socket.send("I have received your message");
}
};
以下是通过云函数向所有 WebSocket 连接发送消息示例:
import cloud from "@/cloud-sdk";
exports.main = async function (ctx) {
const sockets: Set<WebSocket> = cloud.sockets;
sockets.forEach((socket) => {
socket.send("Everyone will receive this message");
});
return "ok";
};
更多用法请参考: https://github.com/websockets/ws
客户端 WebSocket 连接
const wss = new WebSocket("wss://your-own-appid.lafyun.com");
wss.onopen = (socket) => {
console.log("connected");
wss.send("hi");
};
wss.onmessage = (res) => {
console.log("收到了新的信息......")
console.log(res.data);
};
wss.onclose = () => {
console.log("closed");
};