搜索插件、代码仓与 APP 分类

插件详情v1.0.0

ws

WS:一个紧凑且高效的 WebSocket 库。轻松在实时应用中建立、管理和重新连接 WebSocket 连接。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
2820
喜欢数
87
Pub 分数
140

安装插件

flutter pub add ws

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

WS 是一个轻量级且高效的 WebSocket 库,专为 Flutter 设计,用于应用中的实时通信。它能够无缝建立、管理和自动重连跨多个平台的 WebSocket 连接。该库注重性能和简洁性,支持 Android、iOS、Web、macOS、Windows 和 Linux,非常适合实时数据流、聊天应用和实时仪表板。该库优先考虑可靠性与低开销,为开发者提供简洁的 API,以最少的努力集成双向通信。

适合场景

  • 实时聊天应用
  • 实时数据流
  • 物联网设备通信
  • 在线游戏
  • 实时分析仪表板

主要特点

  • 自动重连
  • 低内存占用
  • 跨平台支持
  • 简单 API
  • 高效的消息处理
  • 安全 WebSocket (wss) 支持

适合对象

  • 开发实时功能的开发者
  • 需要持久连接的应用程序
  • 高性能消息系统
  • 跨平台实时应用

使用建议

  • 在不稳定的网络中需要仔细处理错误
  • 有限的内置序列化
  • 不适用于非WebSocket协议
  • 手动管理连接状态
  • 依赖外部 JSON 或消息解析库

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

WS: Cross-platform WebSocket client

Pub Actions Status Coverage License: MIT Linter GitHub stars

The ws package provides a cross-platform WebSocket client for both Dart and Flutter applications. It allows you to connect to a WebSocket server, send and receive messages, and handle the connection state changes.


Installation

Add the following dependency to your pubspec.yaml file:

dependencies:
  ws: <version>

Properties

  • reconnectTimeout: A read-only property that returns the reconnect timeout. The default value is 5 seconds.
  • state: A read-only property that returns the current WebSocket connection state.
  • stateChanges: A read-only property that returns a stream of WebSocket connection state changes.
  • stream: A read-only property that returns a stream of message events handled by the WebSocket.
  • metrics: A read-only property that returns a WebSocketMetrics object with metrics about the WebSocket connection.

Methods

  • connect(String url): Connects to the WebSocket server specified by the URL argument.
  • disconnect([int? code = 1000, String? reason = 'NORMAL_CLOSURE']): Closes the WebSocket connection. You can optionally pass a numeric code and a reason string to the method to send close information to the remote peer.
  • add(Object data): Sends data on the WebSocket connection. The data can be either a String or a List of integers holding bytes.
  • close([int? code = 1000, String? reason = 'NORMAL_CLOSURE']): Permanently stops the WebSocket connection and frees all resources. After calling this method, the WebSocket client is no longer usable.

Options

The WebSocketOptions class provides a configurable set of options for setting up a WebSocket connection on both VM (Virtual Machine) and JS (JavaScript) platforms. This class supports a variety of settings including connection retry strategies, subprotocols, timeouts, message interceptors, and platform-specific configurations.

To use WebSocketOptions, instantiate it directly with the desired configuration for your platform. Use the .vm() factory for VM platform settings and .js() factory for JS platform settings. The .selector() factory can be used to construct options depending on the current platform, allowing for flexible configuration across different environments.

Common Options

Common configuration options applicable across VM and JS platforms:

Option Description
connectionRetryInterval Specifies the Backoff full jitter strategy for reconnecting. Allows tweaks for the reconnect backoff algorithm (min delay, max delay). If not specified, reconnecting is disabled.
protocols Specifies the subprotocols the client is willing to speak.
timeout Specifies the maximum time to wait for the connection to be established. Defaults to 30 seconds if not specified.
afterConnect Specifies the callback function to be called after the connection is established, but before the client is allowed to send user messages.
interceptors Specifies the interceptors for WebSocket messages.
VM Platform Options

Specific to VM (Mobile, Desktop, Server, Console) platform. Not to be used on the web platform.

  • Includes all common options.
  • headers: Specifies additional HTTP headers for setting up the connection. Certain headers are controlled by the WebSocket connection process and will be ignored if passed.
  • compression: If provided, configures the WebSocket to negotiate with the specified CompressionOptions.
  • customClient: Allows specifying a custom HttpClient.
  • userAgent: Allows specifying a custom UserAgent.
JS Platform Options

Specific to JS (Browser) platform. Not to be used on the VM platform.

  • Includes all common options.
  • useBlobForBinary: Specifies if Uint8List should be sent as Blob or as typed data. Defaults to sending as typed data.

Example

Example of using the ws library to connect to a WebSocket server

Reconnection

The ws package provides a cross-platform WebSocket client that supports automatic reconnection in case of connection loss. The client automatically tries to reconnect to the server when the connection is lost. To handle reconnection-related events, you can register listeners for the stateChanges stream, which notifies you about changes in the connection state. When the connection is closed, the client tries to reconnect with a delay, which increases exponentially with each unsuccessful attempt to prevent overloading the server.

Metrics

The ws package provides a cross-platform WebSocket client that supports metrics. The client automatically collects metrics about the number of sent and received messages, as well as the number of sent and received bytes. To get the metrics, you can use the metrics property, which returns a WebSocketMetrics object. The metrics are updated on demand, so you can get the latest values at any time.

JSON

The ws package provides a cross-platform WebSocket client that supports JSON. The client automatically decodes incoming messages from JSON to Dart objects. To get the decoded messages, you can use the client.stream.json property, which returns a Stream<Map<String, Object?>> of decoded messages.

Features and Roadmap

  • ✅ Cross-platform WebSocket client for Dart and Flutter
  • ✅ Support for secure WebSocket connections wss://
  • ✅ Specifying custom protocols
  • ✅ Connection state changes
  • ✅ Reconnection to new URL
  • ✅ Concurrency
  • ✅ Backoff full jitter strategy for reconnection attempts
  • ✅ Handy stream of messages with automatic JSON decoding
  • ✅ Metrics & TX/RX bytes and counters
  • ✅ Platform-specific options
  • ✅ Connection timeout
  • ✅ Creating Web Socket client from custom implementation
  • ✅ Fake client for testing
  • ✅ Custom exceptions
  • ✅ 90% test coverage
  • ✅ First message after connection/reconnection
  • ✅ Interceptors (middlewares)

More resources

Coverage

Changelog

Refer to the Changelog to get all release notes.

Maintainers

Matiunin Mikhail aka Plague Fox

Funding

If you want to support the development of our library, there are several ways you can do it:

We appreciate any form of support, whether it's a financial donation or just a star on GitHub. It helps us to continue developing and improving our library. Thank you for your support!

License

MIT

Tags

web, socket, ws, wss, WebSocket, cross, platform


所属分类

依赖

依赖清单 1 项

源码仓库

使用此插件的项目

暂无相关数据。