WebSocket
在 JavaScript 中使用 Rust 客户端打开 WebSocket 连接。
支持的平台
This plugin requires a Rust version of at least 1.77.2
Platform | Level | Notes |
---|---|---|
windows | ||
linux | ||
macos | ||
android | ||
ios |
设置
首先安装 WebSocket 插件。
使用项目的包管理器来添加依赖。
npm run tauri add websocket
yarn run tauri add websocket
pnpm tauri add websocket
deno task tauri add websocket
bun tauri add websocket
cargo tauri add websocket
-
在你的
Cargo.toml
文件中添加以下内容来安装 websocket 插件。src-tauri/Cargo.toml [dependencies]tauri-plugin-websocket = "2.0.0"# 或者使用 Git:tauri-plugin-websocket = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" } -
修改
lib.rs
来初始化插件。src-tauri/src/lib.rs fn run() {tauri::Builder::default().plugin(tauri_plugin_websocket::init()).run(tauri::generate_context!()).expect("error while running tauri application");} -
使用你喜欢的 JavaScript 包管理器安装 JavaScript Guest 绑定。
npm install @tauri-apps/plugin-websocketyarn add @tauri-apps/plugin-websocketpnpm add @tauri-apps/plugin-websocketdeno add npm:@tauri-apps/plugin-websocketbun add @tauri-apps/plugin-websocket
用法
WebSocket 插件可以在 JavaScript 中使用。
import WebSocket from '@tauri-apps/plugin-websocket';
const ws = await WebSocket.connect('ws://127.0.0.1:8080');
ws.addListener((msg) => { console.log('Received Message:', msg);});
await ws.send('Hello World!');
await ws.disconnect();
权限
默认情况下,所有具有潜在危险的插件命令和范围都会被阻止且无法访问。您必须修改 capabilities
文件夹中的配置来启用它们。
参见能力概览以获取更多信息,以及插件的分步导览来调整插件权限。
{ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "main-capability", "description": "Capability for the main window", "windows": ["main"], "permissions": ["websocket:default"]}
Default Permission
Allows connecting and sending data to a WebSocket server
This default permission set includes the following:
allow-connect
allow-send
Permission Table
Identifier | Description |
---|---|
|
Enables the connect command without any pre-configured scope. |
|
Denies the connect command without any pre-configured scope. |
|
Enables the send command without any pre-configured scope. |
|
Denies the send command without any pre-configured scope. |
© 2025 Tauri Contributors. CC-BY / MIT