Skip to content
Tauri 中文网

Websocket

使用 JavaScript 中的 Rust 客户端打开 WebSocket 连接。

🌐 Open a WebSocket connection using a Rust client in JavaScript.

🌐 Supported Platforms

This plugin requires a Rust version of at least 1.77.2

Platform Level Notes
windows
linux
macos
android
ios

🌐 Setup

安装 websocket 插件即可开始使用。

🌐 Install the websocket plugin to get started.

使用你项目的包管理器添加依赖:

npm run tauri add websocket

🌐 Usage

websocket 插件在 JavaScript 中可用。

🌐 The websocket plugin is available in JavaScript.

import WebSocket from '@tauri-apps/plugin-websocket';
// when using `"withGlobalTauri": true`, you may use
// const WebSocket = window.__TAURI__.websocket;
const ws = await WebSocket.connect('ws://127.0.0.1:8080');
const removeListener = ws.addListener((msg) => {
console.log('Received Message:', msg);
});
await ws.send('Hello World!');
// optionally remove the listener
removeListener();
await ws.disconnect();

🌐 Permissions

默认情况下,所有潜在危险的插件命令和作用域都会被阻止,无法访问。你必须在 capabilities 配置中修改权限以启用这些功能。

🌐 By default all potentially dangerous plugin commands and scopes are blocked and cannot be accessed. You must modify the permissions in your capabilities configuration to enable these.

有关更多信息,请参见功能概览,有关使用插件权限的分步指南,请参见分步指南

🌐 See the Capabilities Overview for more information and the step by step guide to use plugin permissions.

src-tauri/capabilities/default.json
{
"$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

websocket:allow-connect

Enables the connect command without any pre-configured scope.

websocket:deny-connect

Denies the connect command without any pre-configured scope.

websocket:allow-send

Enables the send command without any pre-configured scope.

websocket:deny-send

Denies the send command without any pre-configured scope.


Tauri 中文网 - 粤ICP备13048890号
Nodejs.cn 旗下网站