Flutter实时通信插件pusher_client_token_fixed的使用

Flutter实时通信插件pusher_client_token_fixed的使用

概述

pusher_client_token_fixed 是一个为 Flutter 设计的用于实时通信的插件,支持 Android 和 iOS 平台。它封装了 pusher-websocket-javapusher-websocket-swift 库。

功能

  • 支持官方 Pusher 服务器和自托管的 Laravel WebSocket 服务器(如 laravel-websockets)。
  • 兼容 Android API 16 及以上版本和 iOS 9.0 及以上版本。

目录

安装

pubspec.yaml 文件中添加依赖:

dependencies:
    pusher_client_token_fixed: ^2.0.0

配置

对于 iOS

确保 Podfile 的最小部署目标为 9.0:

platform :ios, '9.0'

如果使用本地 Pusher 服务器订阅私有频道时遇到问题,可以在 ios/Runner/Info.plist 中添加以下内容:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

或者指定具体的域名:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>
对于 Android

如果启用了 R8 或 ProGuard 代码混淆,需要在 android/app/build.gradle 中添加规则:

buildTypes {
  release {
    minifyEnabled true
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  }
}

然后在 android/app/proguard-rules.pro 中添加:

-keep class com.github.chinloyal.pusher_client_token_fixed.** { *; }

API 概览

以下是 API 的概要:

PusherOptions options = PusherOptions(
    host: 'example.com',
    wsPort: 6001,
    encrypted: false,
    auth: PusherAuth(
        'http://example.com/auth',
        headers: {
            'Authorization': 'Bearer $token',
        },
    ),
);

PusherClient pusher = PusherClient(
    YOUR_APP_KEY,
    options,
    autoConnect: false
);

// 在实例化之后连接
pusher.connect();

pusher.onConnectionStateChange((state) {
    print("previousState: ${state.previousState}, currentState: ${state.currentState}");
});

pusher.onConnectionError((error) {
    print("error: ${error.message}");
});

// 订阅私有频道
Channel channel = pusher.subscribe("private-orders");

// 绑定监听事件
channel.bind("order-status-updated", (PusherEvent event) {
    print(event.data);
});

// 取消订阅频道
pusher.unsubscribe("private-orders");

// 断开连接
pusher.disconnect();

Pusher 构造函数

构造函数接受应用密钥和 Pusher 选项对象:

PusherClient pusher = PusherClient(YOUR_APP_KEY, PusherOptions());

如果使用私有、存在或加密频道,则需要提供 PusherAuth 进行身份验证:

PusherAuth auth = PusherAuth(
    // 使用完整的 URL
    'http://example.com/auth',
    headers: {
        'Authorization': 'Bearer $token',
    },
);

PusherOptions options = PusherOptions(
    auth: auth
);

PusherClient pusher = PusherClient(YOUR_APP_KEY, options);

Pusher 选项配置

Pusher 选项对象用于配置大多数功能:

方法 参数 描述
encrypted bool 是否使用 TLS 连接
auth PusherAuth 设置身份验证选项
host String 连接的主机名
wsPort int 未加密连接的端口
wssPort int 加密连接的端口
cluster String 设置连接的集群
activityTimeout int 不活动时触发 ping 的毫秒数
pongTimeout int 等待 pong 响应的最大毫秒数
maxReconnectionAttempts int 重连尝试的最大次数
maxReconnectGapInSeconds int 两次重连之间最大延迟

重新连接

调用 connect() 方法可以重新连接:

pusher.connect();

断开连接

使用 disconnect() 方法断开连接:

pusher.disconnect();

订阅频道

频道使用名称进行标识和订阅。事件绑定到频道并由名称识别:

Channel channel = pusher.subscribe("private-orders");

绑定事件

有两种类型的事件:协议相关的事件和应用程序事件:

channel.bind("order-status-updated", (PusherEvent event) {
    print(event.data);
});

触发客户端事件

一旦授权成功,可以在频道上触发客户端事件:

channel.trigger("client-istyping", {"name": "Bob"});

获取连接套接字ID

连接后可以获取当前客户端连接的唯一标识符(套接字ID):

String socketId = pusher.getSocketId();

解决常见问题

iOS 日志不输出

iOS 日志不会输出到 Flutter 控制台,但可以通过 Xcode 查看日志。

iOS 订阅私有频道

如果使用本地 Pusher 服务器且无法订阅私有频道,请在 ios/Runner/Info.plist 中添加以下内容:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

或者指定具体的域名:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

示例代码

以下是完整的示例代码:

import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:pusher_client_token_fixed/pusher_client_token_fixed.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  PusherClient pusher;
  Channel channel;

  [@override](/user/override)
  void initState() {
    super.initState();

    String token = getToken();

    pusher = new PusherClient(
      "app-key",
      PusherOptions(
        // 如果在本地 Android 上使用 10.0.2.2
        host: 'localhost',
        encrypted: false,
        auth: PusherAuth(
          'http://example.com/broadcasting/auth',
          headers: {
            'Authorization': 'Bearer $token',
          },
        ),
      ),
      enableLogging: true,
    );

    channel = pusher.subscribe("private-orders");

    pusher.onConnectionStateChange((state) {
      log("previousState: ${state.previousState}, currentState: ${state.currentState}");
    });

    pusher.onConnectionError((error) {
      log("error: ${error.message}");
    });

    channel.bind('status-update', (event) {
      log(event.data);
    });

    channel.bind('order-filled', (event) {
      log("Order Filled Event" + event.data.toString());
    });
  }

  String getToken() => "super-secret-token";

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Example Pusher App'),
        ),
        body: Center(
            child: Column(
          children: [
            ElevatedButton(
              child: Text('Unsubscribe Private Orders'),
              onPressed: () {
                pusher.unsubscribe('private-orders');
              },
            ),
            ElevatedButton(
              child: Text('Unbind Status Update'),
              onPressed: () {
                channel.unbind('status-update');
              },
            ),
            ElevatedButton(
              child: Text('Unbind Order Filled'),
              onPressed: () {
                channel.unbind('order-filled');
              },
            ),
            ElevatedButton(
              child: Text('Bind Status Update'),
              onPressed: () {
                channel.bind('status-update', (PusherEvent event) {
                  log("Status Update Event" + event.data.toString());
                });
              },
            ),
            ElevatedButton(
              child: Text('Trigger Client Typing'),
              onPressed: () {
                channel.trigger('client-istyping', {'name': 'Bob'});
              },
            ),
          ],
        )),
      ),
    );
  }
}

更多关于Flutter实时通信插件pusher_client_token_fixed的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter实时通信插件pusher_client_token_fixed的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


pusher_client_token_fixed 是一个用于在 Flutter 应用中实现实时通信的插件。它是基于 Pusher 平台的一个客户端库,允许你轻松地集成实时功能到你的应用中。Pusher 提供了一种简单的方式来处理实时事件、频道订阅和消息传递。

安装

首先,你需要在 pubspec.yaml 文件中添加依赖:

dependencies:
  pusher_client_token_fixed: ^1.0.0

然后运行 flutter pub get 来安装依赖。

基本用法

  1. 初始化 Pusher 客户端

    首先,你需要初始化 Pusher 客户端。你需要 Pusher 的 appKey,你可以在 Pusher 的 Dashboard 中找到它。

    import 'package:pusher_client_token_fixed/pusher_client_token_fixed.dart';
    
    PusherClient pusher;
    
    void initPusher() {
      pusher = PusherClient(
        "YOUR_APP_KEY",
        PusherOptions(
          cluster: "YOUR_CLUSTER",
          auth: PusherAuth(
            "YOUR_AUTH_ENDPOINT",
            headers: {
              "Authorization": "Bearer YOUR_TOKEN",
            },
          ),
        ),
        enableLogging: true,
      );
    }
    
  2. 连接到 Pusher

    在初始化之后,你需要连接到 Pusher 服务:

    pusher.connect();
    
  3. 订阅频道

    你可以订阅一个频道来接收实时消息:

    Channel channel = pusher.subscribe("channel_name");
    
  4. 绑定事件

    你可以绑定事件监听器来处理接收到的消息:

    channel.bind("event_name", (event) {
      print("Received event: ${event.data}");
    });
    
  5. 取消订阅和断开连接

    当你不再需要实时通信时,可以取消订阅并断开连接:

    pusher.unsubscribe("channel_name");
    pusher.disconnect();
    

示例

以下是一个完整的示例,展示了如何使用 pusher_client_token_fixed 插件:

import 'package:flutter/material.dart';
import 'package:pusher_client_token_fixed/pusher_client_token_fixed.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  PusherClient pusher;
  String message = "No message yet";

  [@override](/user/override)
  void initState() {
    super.initState();
    initPusher();
  }

  void initPusher() {
    pusher = PusherClient(
      "YOUR_APP_KEY",
      PusherOptions(
        cluster: "YOUR_CLUSTER",
        auth: PusherAuth(
          "YOUR_AUTH_ENDPOINT",
          headers: {
            "Authorization": "Bearer YOUR_TOKEN",
          },
        ),
      ),
      enableLogging: true,
    );

    pusher.connect();

    Channel channel = pusher.subscribe("my-channel");

    channel.bind("my-event", (event) {
      setState(() {
        message = event.data;
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Pusher Example'),
        ),
        body: Center(
          child: Text(message),
        ),
      ),
    );
  }

  [@override](/user/override)
  void dispose() {
    pusher.disconnect();
    super.dispose();
  }
}
回到顶部