Coder Social home page Coder Social logo

centrifugal / centrifuge-dart Goto Github PK

View Code? Open in Web Editor NEW
97.0 8.0 30.0 509 KB

Dart (Flutter) client SDK for bidirectional communication with Centrifugo and Centrifuge-based server over WebSocket

Home Page: https://pub.dartlang.org/packages/centrifuge

License: MIT License

Dart 97.50% Java 0.14% Objective-C 0.29% Shell 0.72% Kotlin 0.05% Swift 0.15% HTML 0.58% Ruby 0.50% CSS 0.08%
dart flutter centrifugo centrifuge websocket

centrifuge-dart's People

Contributors

fzambia avatar hetao29 avatar holofox avatar mogol avatar robert-virkus avatar synw avatar tiamo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

centrifuge-dart's Issues

ClientDisconnectedError

While the application was in the foreground, the following error occurred in the log records. It wasn't in the background.

Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: ClientDisconnectedError
       at Transport.sendAsyncMessage(transport.dart:155)
       at ClientImpl._onPing(client.dart:711)
       at ClientImpl._onPush(client.dart:719)
       at Transport._onData.<fn>.<fn>(transport.dart:266)
       at _GrowableList.forEach(_GrowableList.java)
       at Transport._onData.<fn>(transport.dart:262)

image

Unable to send RPC request

Hello again! I noticed that RPC requests are not sent. The problem occurs when deserializing and serializing data. Shouldn't we use the type Uint8List instead of List<int>?

To clarify the situation, now the centrifuge client on Dart allows you to send RPC requests in binary form (List<int>).

Before bringing to this form, I convert the bodies of an RPC request through the .writeToBuffer() or

utf8.encode(jsonEncode(request.toProto3Json());

method, it is worth noting that the binary result of these operations is different;

What should I do to correctly send a request? A little later I will try to supplement the information about the problem I am facing.

Make all async functions return a Future

Would it be possible to return a future for all async methods? I have noticed that some async methods return void and not Future<void> which make then non awaitable. Is this on purpose?

Ex: I would like to await connect but can't because it does not return a future:

@override
  void connect() async {
    return _connect();
  }

Here _connect returns a future, and connect would be great this way:

 Future<void> connect() async {
   return await _connect();
 }
// or the short way
 Future<void> connect() async => _connect();

Is it possible or the actual way is by design?

How to catch exception on publish?

My publish response is throwing an exception. I am trying to catch the exception but it doesn't work:

    try {
      subscription.publish(data);
    } catch (e) {
      print(e);
    }
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: Error{code: 0, message: Points already collected within 24h}
#0      Transport._processResult
package:centrifuge/src/transport.dart:148
#1      Transport.sendMessage
package:centrifuge/src/transport.dart:95
<asynchronous suspension>
#2      ClientImpl.publish
package:centrifuge/src/client.dart:183
<asynchronous suspension>

I return the error like this on my backend:

{ error: { message: e.message } }

I wonder if it would be better to not return an error but something like a custom error to now have it convert into an exception? Something like

{ result: { data: { success: false, message: "Foo" } } };

Cannot add new events after calling close

I saw this error on Firebase. I am trying to unsubscribe channel.

Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: Bad state: Cannot add new events after calling close
       at _BroadcastStreamController.add(_BroadcastStreamController.java)
       at SubscriptionImpl._addUnsubscribe(subscription.dart:244)
       at SubscriptionImpl.moveToUnsubscribed(subscription.dart:173)
       at IMController.unsubscribe(im_controller.dart:157)

this is my unsubscribe code:

  Future<void> unsubscribe(String channel) async {
    var a = _imClient.getSubscription(channel);
    if (a != null) {
      await a.unsubscribe();  //line 157
      _imClient.removeSubscription(a);
    }
  }

Is it possible to make use of proxy methods?

Hi,

I am trying to implement proxy_subscribe_endpoint. The endpoint gets called on my backend on subscribe, I return a message like this:

{
  "result": {
    "data": {
      "hello": "world"
    }
  }
}

However, on the subscribeSuccessStream event I only receive SubscribeSuccessEvent{isResubscribed: false, isRecovered: false}

Is this functionality implemented already? I am trying to respond to the subscribing user with some initial user information.

Physical device and localhost:8000

Anyone got an easy way to make the sample app running on my physical Nexus 5x find the localhost:8000 on my laptop over USB ?

I have my nexus 5x being used to test Chat but it of course cant find 127.0.0.1 or localhost to read the server on my laptop.

Got 2 ideas:

  1. Use Intlets ( which is like ngrok) and use a public cloud proxy that points all the way down to the local laptop and then the gateway points it to the Server. Thats a bigger project.
  2. No idea except some stuff about USB tethering on the internet. Looks like i

Use relative imports everywhere

My ide gets confused about the types sometimes when I read this library's code. I think this is because there are some mixed relative and absolute imports for internal files: sometimes it is relative and in some other places library files are imported with package:

I suggest that we move all internal imports to relative to avoid namespace confusions and have a better coding experience

Does it work on the web

I tried to run the chat example on the web but it actually does not want to connect. It just hangs on the connection step, no output

Supporting Centrifugo v3

Hi, what would be required in principle to support v3 of the protocol? I would assume and hope that "only" the proto needs to be exchanged and the commands would need to be re-generated, is that roughly right?
Could the client in principle detect the server side version and decide during runtime which command encoder/decoder to use?

Bad state: StreamSink is closed

The Firebase log record, which is usually seen on Oppo devices, is as follows:

Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: Bad state: StreamSink is closed
       at _WebSocketImpl.add(_WebSocketImpl.java)
       at DelegatingStreamSink.add(stream_sink.dart:35)
       at _CompleterSink.add(sink_completer.dart:88)
       at WebSocketChannelExtension.sendData(channel.dart:20)
       at Transport.sendAsyncMessage(transport.dart:162)
       at ClientImpl._onPing(client.dart:711)
       at ClientImpl._onPush(client.dart:719)
       at Transport._onData.<fn>.<fn>(transport.dart:266)
       at _GrowableList.forEach(_GrowableList.java)
       at Transport._onData.<fn>(transport.dart:262)

I think it is seen in the application that is pending in the background.

image

A few more examples

At the moment the demo works :)
I got it working after a few hours. Great stuff and well abstracted.

But i think that we should add an example that is little more data driven so its easier to play around with Centrifuge.

Use this as a basis.
https://github.com/magicwave/mws_mqtt_client
which currently uses: https://github.com/shamblett/mqtt_client
Its for MQTT but is a good example.

It shows the server connected, and allows you to connect.
Screenshot 2019-04-08 at 09 43 38

It allows you to make new channels / topics, so you can play around.
Screenshot 2019-04-08 at 09 43 53

It allows you to test putting data into those channels and see it coming back.

Screenshot 2019-04-08 at 09 44 22

Maybe add login - it does not have it yet.


Then it would be good to add a few examples to really show off how powerful centrifuge can be !

Maybe we should host here ?

I can start on the following below:

  1. A Classic Chat app example.

https://github.com/amsokol/flutter-grpc-tutorial

  • At the moment it uses GRPC and so i just have to replace that with the centrifuge-dart calls.
  1. A real time document collaboration.

https://github.com/memspace/zefyr

zefyr-1

  • It has a real time update mechanism based on Quill Delta and so we can tap into that. There is golang code so we can add that to the golang examples to work in tandem with the Dart code.
  • Will add many user cursors later. Just like you see in Google docs.
  1. A Cal App is a good example also
  • So peoples cals stay in sync on their many devices.

token not accepted for dart client but works for other clients

I am using connecting using a secret token to connect to the sever, but on the server, I am getting the following error

{"level":"info","client":"be291d0f-fafd-4d0e-a201-e518d428b5e3","data":"\ufffd\u0001\b\u0001\u0010\u0000\u001a\ufffd\u0001\n\ufffd\u0001eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJUZXN0IE9yZ2FuaXNhdGlvbiAxIiwic3ViIjoiNWRhYTAyMzgtN2YwYy0xMWVhLWIxMTItZWFlNTU2OWY4NjAxIiwiZXhwIjoxNTg5OTg3NjYxfQ.fwwM8-L4mqdpK2kFteoYmb6TDfoQ3J0oxiyfCmbIDlY","error":"invalid character 'Õ' looking for beginning of value","user":"","time":"2020-05-19T15:15:30Z","message":"error decoding command"}

The following \ufffd\u0001\b\u0001\u0010\u0000\u001a\ufffd\u0001\n\ufffd\u0001 is being added to the token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJUZXN0IE9yZ2FuaXNhdGlvbiAxIiwic3ViIjoiNWRhYTAyMzgtN2YwYy0xMWVhLWIxMTItZWFlNTU2OWY4NjAxIiwiZXhwIjoxNTg5OTg3NjYxfQ.fwwM8-L4mqdpK2kFteoYmb6TDfoQ3J0oxiyfCmbIDlY

This same token works fine for other centrifuge (js, golang, java) clients for the same server.

I have used the example code https://github.com/centrifugal/centrifuge-dart/blob/master/example/console/simple.dart

Unable to subscribe to a private channel

After connecting I am trying to subscribe to a private channel such as $5daa0238-7f0c-11ea-b112-eae5569f8601#5daa0238-7f0c-11ea-b112-eae5569f8601

When I send the subscribe, on the server I am seeing the following in the log

{"level":"info","client":"436bb802-c9a3-471c-99d1-36b94cdf32c3","command":"id:2 method:SUBSCRIBE params:\"\\nJ$5daa0238-7f0c-11ea-b112-eae5569f8601#5daa0238-7f0c-11ea-b112-eae5569f8601\\022\\000\" ","error":"103: permission denied","reply":"id:2 error:<code:103 message:\"permission denied\" > ","user":"5daa0238-7f0c-11ea-b112-eae5569f8601","time":"2020-05-21T15:41:11Z","message":"client command error"}

I am sure this is related to protobuf format, but not sure what to do.
The channel is being recieved as \\nJ$5daa0238-7f0c-11ea-b112-eae5569f8601#5daa0238-7f0c-11ea-b112-eae5569f8601\\022\\000\

I read in the readme for centrifuge-dart, that subscribe to private channels with JWT is supported. So not sure what I am missing. Is there any change required on the server?

@FZambia Sorry was not able to open the old issue.

Null check operator used on a null value (package:centrifuge/src/transport.dart:219:38)

Here is what I get in my logs after trying to connect to a server (using v0.9.1).

      Null check operator used on a null value
      #0      Transport._onDone.<anonymous closure> (package:centrifuge/src/transport.dart:219:38)
      #1      _rootRun (dart:async/zone.dart:1418:47)
      #2      _CustomZone.run (dart:async/zone.dart:1328:19)
      #3      _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
      #4      _BufferingStreamSubscription._sendDone.sendDone (dart:async/stream_impl.dart:394:13)
      #5      _BufferingStreamSubscription._sendDone (dart:async/stream_impl.dart:404:7)
      #6      _BufferingStreamSubscription._close (dart:async/stream_impl.dart:291:7)
      #7      _SyncStreamControllerDispatch._sendDone (dart:async/stream_controller.dart:782:19)
      #8      _StreamController._closeUnchecked (dart:async/stream_controller.dart:637:7)
      #9      _StreamController.close (dart:async/stream_controller.dart:630:5)
      #10     new _WebSocketImpl._fromSocket.<anonymous closure> (dart:_http/websocket_impl.dart:1156:19)
      #11     _rootRunBinary (dart:async/zone.dart:1450:47)
      #12     _CustomZone.runBinary (dart:async/zone.dart:1342:19)
      #13     _CustomZone.runBinaryGuarded (dart:async/zone.dart:1252:7)
      #14     _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:360:15)
      #15     _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:375:9)
      #16     _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:280:7)
      #17     _SinkTransformerStreamSubscription._addError (dart:async/stream_transformers.dart:75:11)
      #18     _SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:113:7)
      #19     _rootRunUnary (dart:async/zone.dart:1434:47)
      #20     _CustomZone.runUnary (dart:async/zone.dart:1335:19)
      #21     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
      #22     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
      #23     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
      #24     _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
      #25     _StreamController._add (dart:async/stream_controller.dart:648:7)
      #26     _StreamController.add (dart:async/stream_controller.dart:596:5)
      #27     _Socket._onData (dart:io-patch/socket_patch.dart:2314:41)
      #28     _rootRunUnary (dart:async/zone.dart:1442:13)
      #29     _CustomZone.runUnary (dart:async/zone.dart:1335:19)
      #30     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
      #31     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
      #32     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
      #33     _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
      #34     _StreamController._add (dart:async/stream_controller.dart:648:7)
      #35     _StreamController.add (dart:async/stream_controller.dart:596:5)
      #36     new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1839:33)
      #37     _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1322:14)
      #38     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
      #39     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)

flutter doctor:

[✓] Flutter (Channel stable, 3.0.4, on macOS 12.4 21F79 darwin-arm, locale
    en-US)
    • Flutter version 3.0.4 at /Users/amirpanahandeh/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 85684f9300 (10 weeks ago), 2022-06-30 13:22:47 -0700
    • Engine revision 6ba2af10bb
    • Dart version 2.17.5
    • DevTools version 2.12.2

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/amirpanahandeh/SDK
    • Platform android-32, build-tools 30.0.3
    • ANDROID_HOME = /Users/amirpanahandeh/SDK
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build
      11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Community Edition (version 2021.1.3)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin version 58.0.3
    • Dart plugin version 211.7727

[✓] VS Code (version 1.71.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.48.0

[✓] Connected device (3 available)
    • iPhone 13 (mobile) • C3B1EC66-7051-4848-ADB5-C35B94E63C3A • ios
      • com.apple.CoreSimulator.SimRuntime.iOS-15-5 (simulator)
    • macOS (desktop)    • macos                                • darwin-arm64
      • macOS 12.4 21F79 darwin-arm
    • Chrome (web)       • chrome                               • web-javascript
      • Google Chrome 104.0.5112.101

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

connect err

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '+' was called on null.

version: 0.2.0

Higher level api

Hi. Trying to learn this library I ended up making a helper class that reduces the api surface and the boilerplate. Commented code and an example are available: https://github.com/synw/centrifuge-dart/tree/connection_manager/example/manager

It looks like this:

final cent = CentrifugoConnectionManager(
      serverUrl: conf.centrifugoUrl, userToken: token)
    ..connect();
  await cent.onConnected;
  final chan = cent.addChannel("chat");
  await chan.subscribe(
      onMessage: (Map<String, dynamic> payload) => print("MSG $payload"));
  await chan.onJoin;
  unawaited(chan.publish(<String, dynamic>{"message": "Foo"}));

This approach is based on callbacks and completers: this way the user does not have to manage half a dozen stream subscriptions. I added a CentrifugoChannel model as a paradigm for the library user

I can't connect(setToken)

ErrorEvent{error: Connect error: ClientDisconnectedError}

I am getting this error. I think the problem is that I can't assign the token properly. How can I use the setToken command like in JS. Also how can I make 'debug:true' as in the code below.

const centrifuge = new Centrifuge('url', {
websocket: WebSocket,
debug: true
});

Raise protobuf package version 0.13.2 to 1.0.1

Hello! Sorry, is it possible to upgrade the protobuf package to the latest?

Because centrifuge >=0.2.0 depends on protobuf ^0.13.2 and my_flutter_app depends on protobuf ^1.0.1, centrifuge >=0.2.0 is forbidden.
So, because my_flutter_app depends on centrifuge ^0.4.1, version solving failed.
pub upgrade failed (1; So, because my_flutter_app depends on centrifuge ^0.4.1, version solving failed.)

Thank you in advance for considering the matter.

Publish Message with JWT

I can successfully connect to Centrifugo server using JWT and setToken() method. Tested with admin panel and i can only receive message.

Whenever i try to send message i get this Unhandled Exception: Error{code: 103, message: permission denied}

Here is what i am trying

 void sendMessage(SendChatMessage message) async {
    final output = jsonEncode({'token': profileInfo.chatToken, 'data' : {'msg': message.message}});
    final data = utf8.encode(output);
    await _subscriptions[message.channel].publish(data);
  }

Reading published data

I am using version ^0.8.0. I was thinking that

socketSubscription.publishStream.listen((event) {
print(event);
});

with this code I can read the data falling into the socket. Although I do not get any problems in the connection, no data falls into the socket.

EDIT: No problem, I couldn't delete the issue.

Bug. Null check operator used on a null value. When centrifugal client close

return _socket!.close();
IntelliJ IDEA 12 09 15-49-29

https://github.com/centrifugal/centrifuge-dart/blame/53dc5a90a97831faafa5bd60f2c8f3237f6a1b6f/lib/src/transport.dart#L84

#0      Transport.close (package:centrifuge/src/transport.dart:84:19)
#1      ClientImpl.disconnect (package:centrifuge/src/client.dart:207:22)
#2      _CentrifugeConnectMixin.close (package:magistral/src/features/socket_connector/data/centrifuge_connector.dart:167:13)
<asynchronous suspension>

Get Domain via config file, to enable cross device testing.

To make cross device testing easier can we change how we set the domain used.

its here at:
https://github.com/centrifugal/centrifuge-dart/blob/master/example/flutter_app/lib/main.dart#L41

Suggest easiest for now is an asset file with a config in it that we read at startup.
Just as here:
https://pub.dartlang.org/packages/global_configuration#pubspec.yaml

Then you can just drop in whichever config you need with the "domain"
For example i am using ngrok to make all devices be able to see the server locally, but also so that i can eavesdrop the connection easily to help debug.

Is this ok with everyone ?

NPE in ClientImpl.disconnect() _transport == null

I have crashlog in firebase:
NoSuchMethodError: The method 'close' was called on null. Receiver: null Tried calling: close()
Transport.close (Transport.java:93)
ClientImpl.disconnect (ClientImpl.java:144)
CentrifugeInteractor.dispose (CentrifugeInteractor.java:47)
CartPharmaciesListPageBLoC._stopCentrifuge (CartPharmaciesListPageBLoC.java:289)
CartPharmaciesListPageBLoC.dispose (CartPharmaciesListPageBLoC.java:156)
_CartPharmaciesListPageState.dispose (_CartPharmaciesListPageState.java:94)

Seems, it happen when invoke _transport.close() when _transport not build yet.

Message recovery

please i'd like to know if message recovery mechanism functionality is working with this client. and if not what would it take to get that working?

Can do android build. Ios is fine

I have tried dev, beta and master channel and none worked.

I think it might be the way my AVD is configured for android.
Need the right SDK ?
Anyone got an idea ?


x-MacBook-Pro: apple$ flutter doctor 
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.3.8, on Mac OS X 10.14.4 18E226, locale en-DE)
[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    ✗ Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit https://flutter.io/setup/#android-setup for detailed instructions.
[✓] iOS toolchain - develop for iOS devices (Xcode 10.2)
[✓] Android Studio (version 3.3)
[✓] VS Code (version 1.33.0)
[✓] Connected device (2 available)

x-MacBook-Pro: apple$ flutter build apk
Initializing gradle...                                              3.2s
Resolving dependencies...                                               
* Error running Gradle:
ProcessException: Process "/Users/apple/workspace/go/src/github.com/centrifugal/centrifuge-dart/example/flutter_app/android/gradlew" exited abnormally:

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/apple/workspace/go/src/github.com/centrifugal/centrifuge-dart/example/flutter_app/android/build.gradle' line: 24

* What went wrong:
A problem occurred evaluating root project 'android'.
> A problem occurred configuring project ':app'.
   > No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
  Command: /Users/apple/workspace/go/src/github.com/centrifugal/centrifuge-dart/example/flutter_app/android/gradlew app:properties


Please review your Gradle project setup in the android/ folder.

getting transport error on connect.

centrihhj

I tried connecting to a remote centrifugo deployment using the code above and got the error below,

centrifugo

I want to add that this is the version of the dart package I'm using centrifuge: ^0.9.2 and the version of the remote deployment is 4.1.2

App crashes after recovering internet connection

I've installed centrifuge lib in my flutter app. Not the version from pub, but directly from my fork of main repo. Suddenly I've experienced a bug: app crashes after recovering internet connection. There were no error messages in console, only 'Lost connection to device'.

Steps to reproduce (on iOS simulator):

  1. With active internet connection, connect to centrifuge on app start
  2. Subscribe to some arbitrary channel
  3. Disconnect from internet for about 30-40 seconds
  4. Enable internet again

After doing that, app crashes after a couple of sesonds.
Tried launching app through Xcode, but when app crashes, there are also no error logs, only Message from debugger: Terminated due to signal 13.

flutter doctor:

[✓] Flutter (Channel dev, v1.4.4, on Mac OS X 10.14.5 18F96h, locale en-RU)
    • Flutter version 1.4.4 at /Users/vanelizarov/flutter
    • Framework revision 3b3f6c7a04 (2 days ago), 2019-03-27 13:56:23 -0700
    • Engine revision 0d83a2ecd1
    • Dart version 2.2.1 (build 2.2.1-dev.2.0 None)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/vanelizarov/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.2)
    • Xcode at /Applications/Xcode-beta.app/Contents/Developer
    • Xcode 10.2, Build version 10P107d
    • ios-deploy 2.0.0
    • CocoaPods version 1.5.3

[✓] Android Studio (version 3.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 33.4.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] VS Code (version 1.32.3)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 2.24.0

[✓] Connected device (2 available)
    • vanelizarov-iphone • c25ab95a7a881c4a4d782f7ebbff2c392d44bb69 • ios • iOS 12.3
    • iPhone Xʀ          • 96D9C935-0DD3-47BA-A9E3-F640322197D6     • ios • com.apple.CoreSimulator.SimRuntime.iOS-12-2 (simulator)

• No issues found!

Handle connection errors

Hello. I'm trying to use a centrifuge to create a simple chat and can't think of a better way to handle connection errors (for example, the user has no internet or the server is not available). Is there any way to do this?

I am unable to connect to the Centrifugo

import 'dart:async';
import 'dart:convert';
import 'package:centrifuge/centrifuge.dart' as centrifuge;
import 'package:flutter/material.dart';
import 'package:mize/constants/api_endpoints.dart';
import 'package:mize/models/notification_model.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:developer' as dev;

class NotificationClient {
late centrifuge.Client _centrifuge;
centrifuge.Subscription? _subscription;
StreamSubscription<centrifuge.ConnectedEvent>? _connectedSub;
StreamSubscription<centrifuge.ConnectingEvent>? _connectingSub;
StreamSubscription<centrifuge.DisconnectedEvent>? _disconnectedSub;
StreamSubscription<centrifuge.ErrorEvent>? _errorSub;

final services = StreamController();

Stream get notifications => services.stream;

// void init() {
// debugPrint('connected');
// const url = ApiEndpoints.websocketurl;
// _centrifuge = centrifuge.createClient(
// url,
// centrifuge.ClientConfig(
// token: ApiEndpoints.centrifugoToken,
// ));
// _centrifuge.connect();
// _subscription?.subscribe();
// }

NotificationClient() {
// debugPrint('connected');
const url = ApiEndpoints.websocketurl;
_centrifuge = centrifuge.createClient(
url,
centrifuge.ClientConfig(
token: ApiEndpoints.centrifugoToken,

    ));
// _centrifuge.connect();
// _subscription?.subscribe();

}
Future connect() async {
_centrifuge.connected.listen((event) {
// onConnect();
Fluttertoast.showToast(
msg: "Connected to Centrifugo server",
backgroundColor: Colors.green,
textColor: Colors.white);
});
_centrifuge.connecting.listen((event) {
// onConnect();
Fluttertoast.showToast(
msg: "Connecting to Centrifugo server",
backgroundColor: Colors.green,
textColor: Colors.white);
});
_centrifuge.disconnected.listen((event) {
Fluttertoast.showToast(
msg: "Centrifugo server disconnected",
backgroundColor: Colors.red,
textColor: Colors.white);
});
_centrifuge.error.listen((event) {
Fluttertoast.showToast(
msg: 'error', backgroundColor: Colors.red, textColor: Colors.white);
print(event);
});
await _centrifuge.connect();
}

Future subscribe(String channel) async {
_subscription = _centrifuge.getSubscription(channel)!;
_subscription?.publication.listen((event) {
final data = utf8.decode(event.data);
final notification = json.decode(data);
final body = notification['body'].toString();
final message = notification['message'].toString();
services.sink.add(NotificationModel(body: body, message: message));
});
_subscription?.subscribing.listen((event) {
Fluttertoast.showToast(
msg: "Subscribing to Centrifugo server",
backgroundColor: Colors.green,
textColor: Colors.white);
});
_subscription?.subscribed.listen((event) {
Fluttertoast.showToast(
msg: "Subscribed to Centrifugo server",
backgroundColor: Colors.green,
textColor: Colors.white);
});
_subscription?.unsubscribed.listen((event) {
Fluttertoast.showToast(
msg: "unsubscribing to Centrifugo server",
backgroundColor: Colors.green,
textColor: Colors.white);
});

await _subscription?.subscribe();

}

Future dispose() async {
await _connectedSub?.cancel();
await _connectingSub?.cancel();
await _disconnectedSub?.cancel();
await _errorSub?.cancel();
}

void listenToNotifications(NotificationModel noti) async {
final output = jsonEncode({'body': noti.body, 'message': noti.message});
print('Sending msg : $output');
final data = utf8.encode(output);
try {
await _subscription?.publish(data);
} on Exception {
rethrow;
}
}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.