app.websocket - WebSocket API

WebSocket 客户端,用于实时双向通信。

要求: macOS 10.15+(旧版系统返回错误) 权限: 需在 manifest 中声明 websocket(L1 standard)

方法

app.websocket.connect(url, opts?)

连接到 WebSocket 服务器。

参数:

  • url (string) - WebSocket URL(ws:// 或 wss://)
  • opts (table, 可选):
    • headers (table, 可选) - 自定义请求头
    • onMessage (function, 可选) - 消息回调 function(id, data, type)
      • id (string) - 连接 ID
      • data (string) - 消息内容(binary 类型为 base64 编码)
      • type (string) - "text""binary"
    • onClose (function, 可选) - 关闭回调 function(id, code, reason)
    • onError (function, 可选) - 错误回调 function(id, message)

返回值: string, error - 连接 ID

local id, err = app.websocket.connect("wss://echo.websocket.org", {
    headers = {
        ["Authorization"] = "Bearer token123"
    },
    onMessage = function(id, data, type)
        app.log.info("收到消息: " .. data)
    end,
    onClose = function(id, code, reason)
        app.log.info("连接关闭: " .. code)
    end,
    onError = function(id, msg)
        app.log.error("WebSocket 错误: " .. msg)
    end
})

app.websocket.send(id, data, opts?)

发送消息。

参数:

  • id (string) - 连接 ID
  • data (string) - 要发送的数据(binary 类型需 base64 编码)
  • opts (table, 可选):
    • type (string, 可选) - "text"(默认)或 "binary"

返回值: boolean, error

-- 发送文本
local ok, err = app.websocket.send(id, "Hello, Server!")

-- 发送 JSON
local ok, err = app.websocket.send(id, app.json.stringify({
    action = "subscribe",
    channel = "updates"
}))

-- 发送二进制数据(base64 编码)
local ok, err = app.websocket.send(id, base64Data, {type = "binary"})

app.websocket.close(id, opts?)

关闭连接。

参数:

  • id (string) - 连接 ID
  • opts (table, 可选):
    • code (number, 可选) - 关闭状态码(默认 1000)
    • reason (string, 可选) - 关闭原因

返回值: boolean, error

local ok, err = app.websocket.close(id)

-- 指定关闭码和原因
local ok, err = app.websocket.close(id, {code = 1001, reason = "Going away"})

app.websocket.closeAll()

关闭所有连接。

返回值: boolean

app.websocket.closeAll()

app.websocket.list()

列出所有活跃连接。

返回值: array - 连接信息数组

local connections = app.websocket.list()
for _, conn in ipairs(connections) do
    app.log.info(string.format("ID: %s, URL: %s, State: %s",
        conn.id, conn.url, conn.state))
end

连接状态(state):"connecting" | "open" | "closing" | "closed"

示例

实时聊天

function MyPlugin:handleChat(context)
    local ws, err = app.websocket.connect("wss://chat.example.com/ws", {
        onMessage = function(id, data, type)
            local msg = app.json.parse(data)
            if msg and msg.text then
                app.notification.show("新消息", msg.text)
            end
        end,
        onError = function(id, msg)
            app.notification.show("连接错误", msg)
        end
    })

    if not ws then
        app.dialog.alert({title = "错误", message = err})
        return
    end

    -- 发送消息
    app.websocket.send(ws, app.json.stringify({
        type = "message",
        text = "Hello from iRightMenu!"
    }))
end

文件变更监控

function MyPlugin:init()
    self.wsId = nil
end

function MyPlugin:handleStartWatch(context)
    if self.wsId then
        app.websocket.close(self.wsId)
    end

    self.wsId = app.websocket.connect("ws://localhost:8080/watch", {
        onMessage = function(id, data)
            local event = app.json.parse(data)
            if event and event.type == "change" then
                app.notification.show("文件变更", event.path)
            end
        end,
        onClose = function(id, code, reason)
            self.wsId = nil
            app.log.info("监控已停止")
        end
    })
end

function MyPlugin:cleanup()
    if self.wsId then
        app.websocket.close(self.wsId)
    end
end

注意事项

  1. macOS 版本:需要 macOS 10.15+,旧版本所有方法返回错误
  2. 连接数限制:每个插件最多 10 个并发连接
  3. 二进制数据:发送和接收二进制数据使用 base64 编码
  4. 资源清理:插件卸载时自动关闭所有连接,也可手动调用 closeAll()
开发者文档
使用帮助
使用说明 脚本菜单 常见问题
脚本开发
开发指南
插件开发
快速开始 开发指南 示例插件
API 参考
概览 API 查询 插件信息 日志 Finder 上下文 插件设置 国际化
UI 与交互
对话框 进度条 系统通知 选择器 WebView 状态栏 Dock
文件与路径
文件操作 路径工具 Finder 操作 废纸篓 扩展属性 元数据 文件监听
数据格式
JSON Plist CSV XML PDF 图片
文本与编码
字符串 正则表达式 日期时间 颜色 加密编码
系统
Shell 命令 进程管理 应用管理 系统信息 AppleScript 快捷指令
系统信息
网络信息 电源/电池 屏幕/外观 音频控制 蓝牙设备 位置服务
网络
HTTP 请求 WebSocket URL 工具
输入与剪贴板
键盘模拟 鼠标模拟 全局热键 剪贴板 窗口管理
存储
SQLite Keychain UserDefaults
媒体
文字识别 二维码
工具
归档 类型标识 分享 定时器 防休眠 并发/协程