패키지, 저장소 및 앱 카테고리 검색

패키지 상세v2.6.0

pusher_channels_flutter

Pusher Channels Flutter 플러그인

30일 다운로드
7.3만
좋아요
169
Pub 점수
35

패키지 설치

flutter pub add pusher_channels_flutter

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

푸셔 채널 플러터 플러그인은 푸셔 채널(실시간 데이터 스트리밍 서비스)에 연결함으로써 플러터 애플리케이션에서 실시간 통신을 가능하게 합니다. 이 플러그인은 앱이 채널과 이벤트를 통해 즉각적인 업데이트를 받을 수 있도록 해주며, 채팅, 알림, 실시간 스코어, 협업 도구와 같은 기능에 이상적입니다. 플러그인은 안드로이드 및 iOS 플랫폼 모두를 지원하며 플러터의 반응형 아키텍처와 원활하게 통합됩니다. 간단한 이벤트 기반 API를 통해 개발자는 채널에 구독하고 이벤트를 듣고, 존재 상태 데이터를 관리할 수 있습니다. 낮은 지연 시간과 확장 가능한 실시간 상호작용을 위해 설계되었습니다.

사용 사례

  • 실시간 채팅 애플리케이션
  • 실시간 스코어 및 스포츠 업데이트
  • 협업 편집 도구
  • 즉시 알림 시스템
  • 사용자 존재 표시기

주요 기능

  • 실시간 이벤트 브로드캐스팅
  • 채널 및 개인 채널 지원
  • 존재 및 구독 관리
  • 크로스 플랫폼 호환성 (iOS 및 Android)
  • 간단한 이벤트 기반 API

적합한 대상

  • 실시간 상호작용 앱을 개발하는 개발자
  • 실시간 데이터 동기화가 필요한 팀
  • 즉시 사용자 알림이 필요한 앱
  • Pusher 백엔드 서비스를 사용하는 프로젝트
  • 동적 콘텐츠 업데이트를 갖춘 플러터 앱

고려 사항

  • Pusher 계정 및 앱 자격 증명이 필요합니다
  • Pusher Channels 백엔드로 제한
  • 인증을 위해 추가 설정이 필요할 수 있습니다
  • 실시간 업데이트를 위해 네트워크 연결에 의존합니다
  • 오프라인 우선 애플리케이션에 적합하지 않습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Pusher Channels Flutter Client

Latest Release Twitter GitHub license likes popularity pub points

This is the Pusher Channels Flutter client.

For tutorials and more in-depth information about Pusher Channels, visit our official docs.

Supported Flutter platforms

Deployment targets
  • iOS 13.0 and above
  • Android 6.0 and above
  • Web Chrome/Edge/Firefox/Safari.

Example Application

By cloning this repository you can check the Flutter example application, a minimal application to connect to a channel and send events.

  • https://github.com/pusher/pusher-channels-flutter/tree/master/example

Table of Contents

Installation

To integrate the plugin in your Flutter App, you need to add the plugin to your pubspec.yaml:

dependencies:
  pusher_channels_flutter: '^1.0.1'
iOS specific installation

The Pusher Channels Flutter plugin adds the pusher-websocket-swift cocoapod to your project. You probably need to run a

$ pod install

in the ios directory.

Android specific installation

Gradle should automatically include the pusher-websocket-java dependency.

Web specific installation

For web this plugin uses pusher-js, you can load it from the Pusher CDN, or add it locally. You probably want to include it in the head of your index.html page:

<head>
  <script
    charset="utf-8"
    src="https://js.pusher.com/8.3.0/pusher.min.js"
  ></script>
  ...
</head>

Initialization

The PusherChannelFlutter class is a singleton, that can be instantiated with getInstance(). Then you need to initialize the client with a number of configuration options, here is a quick example with a number of callbacks options:

PusherChannelsFlutter pusher = PusherChannelsFlutter.getInstance();
try {
  await pusher.init(
    apiKey: API_KEY,
    cluster: API_CLUSTER,
    onConnectionStateChange: onConnectionStateChange,
    onError: onError,
    onSubscriptionSucceeded: onSubscriptionSucceeded,
    onEvent: onEvent,
    onSubscriptionError: onSubscriptionError,
    onDecryptionFailure: onDecryptionFailure,
    onMemberAdded: onMemberAdded,
    onMemberRemoved: onMemberRemoved,
    // authEndpoint: "<Your Authendpoint>",
    // onAuthorizer: onAuthorizer
  );
  await pusher.subscribe(channelName: 'presence-chatbox');
  await pusher.connect();
} catch (e) {
  print("ERROR: $e");
}

After calling init(...) you can connect to the Pusher servers. You can subscribe to channels before calling connect()

Configuration

There are a number of configuration parameters which can be set for the Pusher client. The following table describes for which platform the parameter is available:

parameter Android iOS Web
activityTimeout ✅ ✅ ✅
apiKey ✅ ✅ ✅
authParam ⬜️ ⬜️ ✅
authEndpoint ✅ ✅ ✅
authTransport ⬜️ ⬜️ ✅
cluster ✅ ✅ ✅
disabledTransports ⬜️ ⬜️ ✅
enabledTransports ⬜️ ⬜️ ✅
enableStats ⬜️ ⬜️ ✅
ignoreNullOrigin ⬜️ ⬜️ ✅
logToConsole ⬜️ ⬜️ ✅
maxReconnectGapInSeconds ✅ ✅ ⬜️
maxReconnectionAttempts ✅ ✅ ⬜️
pongTimeout ✅ ✅ ✅
proxy ✅ ⬜️ ⬜️
useTLS ✅ ✅ ⬜️
activityTimeout (double)

After this time (in seconds) without any messages received from the server, a ping message will be sent to check if the connection is still working; the default value is supplied by the server, low values will result in unnecessary traffic.

apiKey (String)

You can get your API_KEY and API_CLUSTER from the Pusher Channels dashboard.

authParams (Map)

Allows passing additional data to authorizers. Supports query string params and headers (AJAX only). For example, following will pass foo=bar via the query string and baz: boo via headers:

final pusher = PusherChannelsFlutter.getInstance()
await pusher.init(
  apiKey: API_KEY,
  cluster: API_CLUSTER,
  authParams: {
    'params': { 'foo': 'bar' },
    'headers': { 'baz': 'boo' }
  }
});

Additional parameters to be sent when the channel authentication endpoint is called. When using ajax authentication the parameters are passed as additional POST parameters. When using jsonp authentication the parameters are passed as GET parameters. This can be useful with web application frameworks that guard against CSRF (Cross-site request forgery).

CSRF

If you require a CSRF header for incoming requests to the private channel authentication endpoint on your server, you should add a CSRF token to the auth hash under headers. This is applicable to frameworks which apply CSRF protection by default.

final pusher = await pusher.init(
  apiKey: API_KEY,
  cluster: API_CLUSTER,
  authParams: {
    'params': { 'foo': 'bar' },
    'headers': { 'X-CSRF-Token': 'SOME_CSRF_TOKEN' }
  }
);
authEndpoint (String)

The authEndpoint provides a URL that the Pusher client will call to authorize users for a presence channel. On how to implement an authorization service please check here:

https://pusher.com/docs/channels/server_api/authenticating-users/

cluster (String)

Specifies the cluster that pusher-js should connect to. If you'd like to see a full list of our clusters, click here. If you do not specify a cluster, mt1 will be used by default.

useTLS (bool)

Whether or not you'd like to use TLS encrypted transport or not, default is true

Event Callback parameters

The following functions are callbacks that can be passed to the init() method. All are optional.

onEvent
void onEvent(PusherEvent event) {
  print("onEvent: $event");
}

Called when a event is received by the client. The global event handler will trigger on events from any channel.

onSubscriptionSucceeded
void onSubscriptionSucceeded(String channelName, dynamic data) {
  print("onSubscriptionSucceeded: $channelName data: $data");
}

use this if you want to be informed of when a channel has successfully been subscribed to, which is useful if you want to perform actions that are only relevant after a subscription has succeeded. For example querying the members for presence channel.

onSubscriptionError
void onSubscriptionError(String message, dynamic e) {
  print("onSubscriptionError: $message Exception: $e");
}

use this if you want to be informed of a failed subscription attempt, which you could use, for example, to then attempt another subscription or make a call to a service you use to track errors.

onDecryptionFailure
void onDecryptionFailure(String event, String reason) {
  print("onDecryptionFailure: $event reason: $reason");
}

only used with private encrypted channels - use this if you want to be notified if any messages fail to decrypt.

onMemberAdded
void onMemberAdded(String channelName, PusherMember member) {
  print("onMemberAdded: $channelName member: $member");
}

Called when a member is added to the presence channel.

onMemberRemoved
void onMemberRemoved(String channelName, PusherMember member) {
  print("onMemberRemoved: $channelName member: $member");
}

Called when a member is removed to the presence channel.

onAuthorizer

When passing the onAuthorizer() callback to the init() method, this callback is called to request auth information. For more information on how to generate the correct information, please look here: https://pusher.com/docs/channels/library_auth_reference/auth-signatures/

dynamic onAuthorizer(String channelName, String socketId, dynamic options) async {
  return {
    "auth": "foo:bar",
    "channel_data": '{"user_id": 1}',
    "shared_secret": "foobar"
  };
}
onConnectionStateChange
void onConnectionStateChange(dynamic currentState, dynamic previousState) {
  print("Connection: $currentState");
}

use this if you want to use connection state changes to perform different actions / UI updates The different states that the connection can be in are:

  • CONNECTING - the connection is about to attempt to be made
  • CONNECTED - the connection has been successfully made
  • DISCONNECTING - the connection has been instructed to disconnect and it is just about to do so
  • DISCONNECTED - the connection has disconnected and no attempt will be made to reconnect automatically
  • RECONNECTING - an attempt is going to be made to try and re-establish the connection
onError
void onError(String message, int? code, dynamic e) {
  print("onError: $message code: $code exception: $e");
}

use this if you want to be informed of errors received from Pusher Channels e.g. Application is over connection quota. You can find some of the possible errors listed here.

Connection handling

Connecting

To connect to the Pusher network, just call the connect() method.

await pusher.connect();
Disconnecting

To disconnect to the Pusher network, just call the disconnect() method.

await pusher.disconnect();
Reconnection

There are three main ways in which a disconnection can occur:

  • The client explicitly calls disconnect and a close frame is sent over the websocket connection
  • The client experiences some form of network degradation which leads to a heartbeat (ping/pong) message being missed and thus the client disconnects
  • The Pusher server closes the websocket connection; typically this will only occur during a restart of the Pusher socket servers and an almost immediate reconnection should occur

In the case of the first type of disconnection the library will (as you'd hope) not attempt a reconnection.

Subscribing

Public channels

The default method for subscribing to a channel involves invoking the subscribe method of your client object:

final myChannel = await pusher.subscribe(channelName: "my-channel");
Private channels

Private channels are created in exactly the same way as public channels, except that they reside in the 'private-' namespace. This means prefixing the channel name:

final myPrivateChannel = await pusher.subscribe(channelName: "private-my-channel")

Subscribing to private channels involves the client being authenticated. See the Configuration section for the authenticated channel example for more information.

Private encrypted channels

Similar to Private channels, you can also subscribe to a private encrypted channel. This library now fully supports end-to-end encryption. This means that only you and your connected clients will be able to read your messages. Pusher cannot decrypt them.

Like with private channels, you must provide an authentication endpoint. That endpoint must be using a server client that supports end-to-end encryption. There is a demonstration endpoint to look at using nodejs.

The shared secret used to decrypt events is loaded from the same auth endpoint request that is used to authorize your subscription. There is also a mechanism for reloading the shared secret if your encryption master key changes. If an event is encountered that cannot be decrypted, a request is made to your auth endpoint to attempt to load the new shared secret. If that request fails or if the returned secret still cannot decrypt the event then that event will be skipped, the onDecryptionFailure callback function will be called, and the next received event will be processed.

Limitations
  • Client events are not supported on encrypted channels
final privateEncryptedChannel = await pusher.subscribe(channelName: "private-encrypted-my-channel")

There is also an optional callback in the connection delegate when you can listen for any failed decryption events:

optional func void onDecryptionFailure(String event, String reason)
Presence channels

Presence channels are channels whose names are prefixed by presence-.

The resulting channel object has a member: members that contains the active members of the channel.

final myPresenceChannel = await pusher.subscribe(channelName: "presence-my-channel")

You can also provide functions that will be called when members are either added to or removed from the channel. These are available as parameters to init() globally, or to subscribe() per channel.

void onMemberAdded(String channelName, PusherMember member) {
  print("onMemberAdded: $channelName user: $member");
}
void onMemberRemoved(String channelName, PusherMember member) {
  print("onMemberRemoved: $channelName user: $member");
}

Note: The members property of PusherChannel objects will only be set once subscription to the channel has succeeded.

The easiest way to find out when a channel has been successfully subscribed to is to bind to the callback named onSubscriptionSucceeded on the channel you're interested in. It would look something like this:

final pusher = PusherChannelsFlutter.getInstance();
final channels = {};
await pusher.init(
  apiKey: API_KEY,
  cluster: API_CLUSTER,
  authEndPoint: "https://your-server.com/pusher/auth"
);
final myChannel = await pusher.subscribe(
  channelName:'presence-my-channel',
  onSubscriptionSucceeded: (channelName, data) {
    print("Subscribed to $channelName");
    print("I can now access me: ${myChannel.me}")
    print("And here are the channel members: ${myChannel.members}")
  },
  onMemberAdded: (member) {
    print("Member added: $member");
  },
  onMemberRemoved: (member) {
    print("Member removed: $member");
  },
  onEvent: (event) {
    print("Event received: $event");
  },
);

Note that both private and presence channels require the user to be authenticated in order to subscribe to the channel. This authentication can either happen inside the library, if you configured your Pusher object with your app's secret, or an authentication request is made to an authentication endpoint that you provide, again when initializing your Pusher object.

We recommend that you use an authentication endpoint over including your app's secret in your app in the vast majority of use cases. If you are completely certain that there's no risk to you including your app's secret in your app, for example if your app is just for internal use at your company, then it can make things easier than setting up an authentication endpoint.

Unsubscribing

To unsubscribe from a channel, call the unsubscribe() method:

await pusher.unsubscribe("my-channel");

Binding to events

Events can be bound to at 2 levels; globally and per channel. There is an example of this below.

Per-channel events

These are bound to a specific channel, and mean that you can reuse event names in different parts of your client application.

final pusher = PusherChannelsFlutter.getInstance();
await pusher.init(
  apiKey: API_KEY,
  cluster: API_CLUSTER
);
final myChannel = await pusher.subscribe(
  channelName: "my-channel",
  onEvent: (event) {
    print("Got channel event: $event");
  }
);
await pusher.connect();
Global events

You can attach behavior to these events regardless of the channel the event is broadcast to.

final pusher = PusherChannelsFlutter.getInstance();
await pusher.init(
  apiKey: API_KEY,
  cluster: API_CLUSTER,
  onEvent: (event) {
    print("Got event: $event");
  }
);
final myChannel = await pusher.subscribe(
  channelName: "my-channel"
);
PusherEvent

The callbacks you bind receive a PusherEvent:

class PusherEvent {
  String channelName; // Name of the channel.
  String eventName; // Name of the event.
  dynamic data; // Data, usually JSON string. See [parsing event data](#parsing-event-data).
  String? userId; // UserId of the sending event, only for client events on presence channels.
}
Parsing event data

The data property of PusherEvent contains the string representation of the data that you passed when you triggered the event. If you passed an object then that object will have been serialized to JSON. You can parse that JSON as appropriate.

Receiving errors

Errors received from Pusher Channels can be accessed via the onError callback.

void onError(String message, int? code, dynamic e) {
  print("onError: $message code: $code exception: $e");
}

Triggering events

Once a private or presence subscription has been authorized (see authenticating users) and the subscription has succeeded, it is possible to trigger events on those channels. You can do this per channel, or on the global PusherChannelsFlutter instance.

await myChannel.trigger(eventName: "client-my-event", data: ["myName": "Bob"]);

Or on the global pusher instance:

await pusher.trigger(channelName: "my-channel", eventName: "client-my-event", data: ["myName": "Bob"]);

Events triggered by clients are called client events. Because they are being triggered from a client which may not be trusted there are a number of enforced rules when using them. Some of these rules include:

  • Event names must have a client- prefix
  • Rate limits
  • You can only trigger an event when the subscription has succeeded

For full details see the client events documentation.

Get a channel by name

To get the PusherChannel instance from the Pusher instance you can use the getChannel(<channelName>) method:

final channel = pusher.getChannel("presence-channel");

Socket information

To get information from the current socket call the getSocketId() method:

final socketId = await pusher.getSocketId();

Communication

  • If you have found a bug, please open an issue.
  • If you have a feature request, please open an issue.
  • If you want to contribute, please submit a pull request.
  • If you do not receive a timely response, feel free to check our support portal.

Credits

PusherChannelsFlutter is owned and maintained by Pusher.

License

PusherChannelsFlutter is released under the MIT license. See LICENSE for details.

카테고리

의존성

의존성 목록 1 개

  • js^0.7.1

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.