Code Monkey home page Code Monkey logo

web_socket_channel's Introduction

CI pub package package publisher

package:web_socket_channel provides cross-platform StreamChannel wrappers for WebSocket connections.

Docs and Usage

It provides a cross-platform WebSocketChannel API, a cross-platform implementation of that API that communicates over an underlying StreamChannel, an implementation that wraps dart:io's WebSocket class, and a similar implementation that wraps dart:html's.

It also provides constants for the WebSocket protocol's pre-defined status codes in the status.dart library. It's strongly recommended that users import this library with the prefix status.

import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;

main() async {
  final wsUrl = Uri.parse('ws://example.com');
  final channel = WebSocketChannel.connect(wsUrl);

  await channel.ready;

  channel.stream.listen((message) {
    channel.sink.add('received!');
    channel.sink.close(status.goingAway);
  });
}

WebSocketChannel

The WebSocketChannel class's most important role is as the interface for WebSocket stream channels across all implementations and all platforms. In addition to the base StreamChannel interface, it adds a protocol getter that returns the negotiated protocol for the socket, as well as closeCode and closeReason getters that provide information about why the socket closed.

The channel's sink property is also special. It returns a WebSocketSink, which is just like a StreamSink except that its close() method supports optional closeCode and closeReason parameters. These parameters allow the caller to signal to the other socket exactly why they're closing the connection.

WebSocketChannel also works as a cross-platform implementation of the WebSocket protocol. The WebSocketChannel.connect constructor connects to a listening server using the appropriate implementation for the platform.

web_socket_channel's People

Contributors

a-siva avatar analogic avatar brianquinlan avatar chalin avatar chirag729 avatar chungheepark avatar dependabot[bot] avatar devoncarew avatar fox32 avatar franklinyow avatar iota9star avatar jacob314 avatar jakemac53 avatar jithuraj avatar kevmoo avatar leafpetersen avatar leonardorosaa avatar loint avatar lrhn avatar masus04 avatar micimize avatar natebosch avatar nex3 avatar nottsunami avatar osa1 avatar rexios80 avatar srawlins avatar szakarias avatar tempo-riz avatar tvolkert 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  avatar  avatar  avatar

Watchers

 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

web_socket_channel's Issues

An exception if the server sends message when connecting

//server code
class GuiServer(WebSocket):
    def handleConnected(self):
        self.sendMessage(json(initInfo)) #init message

Without sending back initial message connection works, but with it I got the exception:
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'http://localhost:1234#' was not upgraded to websocket
#0 new IOWebSocketChannel._withoutSocket.
package:web_socket_channel/io.dart:84
#1 _invokeErrorHandler (dart:async/async_error.dart:17:29)
#2 _HandleErrorStream._handleError (dart:async/stream_pipe.dart:286:9)
#3 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:168:13)
#4 _rootRunBinary (dart:async/zone.dart:1144:38)
#5 _CustomZone.runBinary (dart:async/zone.dart:1037:19)
#6 _CustomZone.runBinaryGuarded (dart:async/zone.dart:939:7)
#7 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:355:15)
#8 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:373:16)
#9 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:272:7)
#10 _SyncStreamControllerDispatch._sendError (dart:async/stream_controller.dart:768:19)

How to configure connection timeout?

On mobile connection quality can vary depending on the environment conditions.
And if connection is bad sometimes connecting to websocket servers can't be established because of ConnectionTimeOut.
WebSocketChannelException: WebSocketChannelException: SocketException: OS Error: Connection timed out, errno = 110, address = 192.168.2.2, port = 56472

Currently is around a 2min.
This is too long for creating a realtime applications, and sometimes we need to fail faster.
How this timeout can be configured?

This behaviour is annoying because of #21

IOWebSocketChannel loses the first message if they come from the server more than one when connecting

Python server which sends back 2 messages to the client:

class GuiServer(WebSocket):
   def handleConnected(self):
       self.sendMessage(jsonString(data1))
       self.sendMessage(jsonString(data2))
 

My Python websocket client gets this messages ok, but IOWebSocketChannel loses first message and gets only the second when connecting.
If the server sends only 1 message IOWebSocketChannel gets it ok. Not 2. The flutter code:

void createServerChannel() {
 if (serverAddress != null)
   serverChannel = IOWebSocketChannel.connect(serverAddress);
}
....
....
             StreamBuilder(
                 stream: serverChannel.stream,
                 builder: (context, snapshot) {
                   if (snapshot.data != null)
                   {
                     var data = json.decode(snapshot.data); 


How to use protocols?

I make janus client webrtc library.
Janus websocket-server must have 'janus-protocol' protocol property.
I pass arguments to protocols, but could not connect to server.
Janus websocket-server close the connection.

In io.dart, does not pass protocols parameter to WebSocket.connect()

Error: Not found: 'dart:html'

I want to use it in flutter web and flutter, however got these errors

Flutter 1.10.7 • channel dev • https://github.com/flutter/flutter.git
Framework • revision e70236e36c (17 hours ago) • 2019-10-02 09:32:30 -0700
Engine • revision 9e6314d348
Tools • Dart 2.6.0 (build 2.6.0-dev.0.0 1103600280)

===============================

Launching lib/main.dart on iPhone 8 Plus in debug mode...

Compiler message:
../../../.pub-cache/hosted/pub.flutter-io.cn/web_socket_channel-1.0.15/lib/html.dart:8:8: Error: Not found: 'dart:html'
import 'dart:html';
       ^
../../../.pub-cache/hosted/pub.flutter-io.cn/web_socket_channel-1.0.15/lib/html.dart:21:9: Error: Type 'WebSocket' not found.
  final WebSocket _webSocket;
        ^^^^^^^^^
../../../.pub-cache/hosted/pub.flutter-io.cn/web_socket_channel-1.0.15/lib/html.dart:21:9: Error: 'WebSocket' isn't a type.
  final WebSocket _webSocket;
        ^^^^^^^^^
../../../.pub-cache/hosted/pub.flutter-io.cn/web_socket_channel-1.0.15/lib/html.dart:67:14: Error: The method 'WebSocket' isn't defined for the class 'HtmlWebSocketChannel'.
 - 'HtmlWebSocketChannel' is from 'package:web_socket_channel/html.dart' ('../../../.pub-cache/hosted/pub.flutter-io.cn/web_socket_channel-1.0.15/lib/html.dart').
Try correcting the name to the name of an existing method, or defining a method named 'WebSocket'.
      : this(WebSocket(url.toString(), protocols)
             ^^^^^^^^^
../../../.pub-cache/hosted/pub.flutter-io.cn/web_socket_channel-1.0.15/lib/html.dart:74:34: Error: The getter 'WebSocket' isn't defined for the class 'HtmlWebSocketChannel'.
 - 'HtmlWebSocketChannel' is from 'package:web_socket_channel/html.dart' ('../../../.pub-cache/hosted/pub.flutter-io.cn/web_socket_channel-1.0.15/lib/html.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'WebSocket'.
    if (_webSocket.readyState == WebSocket.OPEN) {
                                 ^^^^^^^^^
../../../Downloads/flutter/packages/flutter/lib/src/painting/_network_image_web.dart:56:12: Error: Method not found: 'webOnlyInstantiateImageCodecFromUrl'.
    return ui.webOnlyInstantiateImageCodecFromUrl(resolved); // ignore: undefined_function
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Unhandled exception:
FileSystemException(uri=org-dartlang-untranslatable-uri:dart%3Ahtml; message=StandardFileSystem only supports file:* and data:* URIs)
#0      StandardFileSystem.entityForUri (package:front_end/src/api_prototype/standard_file_system.dart:33:7)
#1      asFileUri (package:vm/kernel_front_end.dart:532:37)
#2      _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:43:6)
#3      asFileUri (package:vm/kernel_front_end.dart:531:22)
#4      writeDepfile (package:vm/kernel_front_end.dart:718:21)
#5      _RootZone.runUnary (dart:async/zone.dart:1379:54)
#6      _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#7      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#8      Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#9      Future._completeWithValue (dart:async/future_impl.dart:522:5)
#10     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:552:7)
#11     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#12     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#13     _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:116:13)
#14     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:173:5)

Compiler failed on /Users/gregliu/data/flutter/nb/lib/main.dart
Error launching application on iPhone 8 Plus.

Lack of ability to configure connection timeouts

On mobile connection quality can vary depending on the environment conditions.
if connection is bad for the moment sometimes connecting to a websocket servers can't be established now, and in this situation ConnectionTimeOut exception must thrown.
Actually this exception throws:
WebSocketChannelException: WebSocketChannelException: SocketException: OS Error: Connection timed out, errno = 110, address = 192.168.2.2, port = 56472
But it take around a 2min before happen.

This is too long for creating a realtime applications with websockets, and sometimes we need to fail faster.

Additionally, this 2 min behaviour is annoying because of issue #21 that closed because issue #25 and flutter/flutter#18204 created. (connecting and already connected states still not differentiable)

How this connection timeout can be configured in this package?

One year ago in issue #22 nex3 answered me, that dart io implementation doesn't expose this API. But it is a superficial answer, because:

  1. HttpClient has this property
    https://api.dartlang.org/stable/2.4.0/dart-io/HttpClient/connectionTimeout.html

  2. if we use dart.io or html implementation directly we can use .timeout function on futures:

_wsFuture = WebSocket.connect(backendUrl)
        .timeout(Duration(seconds: 15))
        .then(_configureWsAfterConnecting);

But when using this package I can't manipulate with connection timeout. If connection doesn't establish in acceptable time I can't fail gracefully.

Is there any support in socket.io ?

I have searched the flutter packages. And try to use web socket to connect socket.io. Seems like there is no support for socket.io client ???

some errors can't be handled in IOWebSocketChannel.connect

Copied from flutter/flutter#21076

IOWebSocketChannel.connect suffers from the problem described here:

https://www.dartlang.org/guides/libraries/futures-error-handling#potential-problem-failing-to-register-error-handlers-early

When I use connect with a URL that can't be resolved (e.g. by having my wifi turned off), then I get an exception that can't be caught by channel.stream.handleError(onError).

All exceptions should be handleable by stream.handleError, particularly as this is what the docs promise: "If there's an error connecting, the channel's stream emits a WebSocketChannelException wrapping that error and then closes."

ref: https://docs.flutter.io/flutter/web_socket_channel.io/IOWebSocketChannel/IOWebSocketChannel.connect.html

flutter: #0      new IOWebSocketChannel._withoutSocket.<anonymous closure> (package:web_socket_channel/io.dart:83:24)
#1      _invokeErrorHandler (dart:async/async_error.dart:13:29)
#2      _HandleErrorStream._handleError (dart:async/stream_pipe.dart:286:9)
#3      _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:168:13)
#4      _rootRunBinary (dart:async/zone.dart:1144:38)
#5      _CustomZone.runBinary (dart:async/zone.dart:1037:19)
#6      _CustomZone.runBinaryGuarded (dart:async/zone.dart:939:7)
#7      _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:355:15)
#8      _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:373:16)
#9      _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:272:7)
#10     _SyncStreamController._sendError (dart:async/stream_controller.dart:767:19)
#11     _StreamController._addError (dart:async/stream_controller.dart:647:7)
#12     _rootRunBinary (dart:async/zone.dart:1144:38)
flutter doctor -v
[✓] Flutter (Channel master, v0.7.1-pre.26, on Mac OS X 10.13.6 17G2208, locale en-GB)
    • Flutter version 0.7.1-pre.26 at /Users/steve/code/flutter
    • Framework revision 510c0eeaff (3 days ago), 2018-08-24 17:19:30 -0700
    • Engine revision 0914926014
    • Dart version 2.1.0-dev.1.0.flutter-ccb16f7282

[✓] Android toolchain - develop for Android devices (Android SDK 28.0.1)
    • Android SDK at /Users/steve/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.1
    • 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-1024-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 9.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 9.4.1, Build version 9F2000
    • ios-deploy 1.9.2
    • CocoaPods version 1.5.3

[✓] Android Studio (version 3.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 26.0.1
    • Dart plugin version 173.4700
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)

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

[✓] Connected devices (1 available)
    • iPhone X • 1E0393AA-EF50-42AA-A244-3279599BE2C1 • ios • iOS 11.4 (simulator)

• No issues found!

How to reconnect and resend request?

My code below,but I caught a ANR ,I want know the correct method to reconnect, thx.

_listen() async {
    _channel.stream.listen((message) {

    }, onError: (error) async {
      Fluttertoast.showToast(msg: "onerror");
      await Future.delayed(Duration(milliseconds: 1000));
      reConnect();
    }, onDone: () async {
      Fluttertoast.showToast(msg: "ondone");
      await Future.delayed(Duration(milliseconds: 1000));
      reConnect();
    });
  }

void reConnect() {
    print("reConnect------>IOWebSocketChannel");
    _channel = IOWebSocketChannel.connect(Address.SOCKET_BASE_URL_RELEASE);
    _channel.sink.add(getHistoryDealParam());
    _channel.sink.add(getRealTimeDeal());
   _listen();
  }

@dart-lang

Possible issue with headers and authentication

Hello!

I'm not sure is an issue of this library but it could be so here it is what I'm stuck in:

I'm using https://pub.dartlang.org/packages/stomp as a communication protocol but using web_socket_channel as websocket library because theirs have problems in Flutter.

With no authentication everything seems to work fine. The problem appears when I try to set a User header (bear with me here I'm not an expert on websockets) it seems that the websocket client library does not keep sending that header.

Since I might be confusing things, here is an example of the problem. As you can see this is the answer sent from the server to the client in flutter after the connect where I've authenticated the user and set it in the headers.

screenshot 2018-12-18 at 17 51 46

Here you can see the next action (subscribe) sent from the client (flutter) to the server where the client header does not appear again.

screenshot 2018-12-18 at 17 52 00

In order to discard the possibility of a bad configuration on the server side I've tested this with a javascript client and it worked well.

Any suggestions of what could be happening here?

Thanks!

Working with self signed certs

Any chance that this package will work with self signed certificates? HttpClient has a configurable callback for this. Would help a lot in prototyping stage...

Flutter: Not working on some devices

While testing out https://flutter.io/cookbook/networking/web-sockets/ example, I found some strange behaviour I cannot explane to myself.

When connecting to a websocket server with an old Android device (Moto XT1092, Android 6.0.1) or the Android emulator (Android P) everything works fine.

When connecting with a Pixel 2 I get an 'Connection not upgraded' exception. Some debugging on the server side shows that the incoming request does not have the 'Upgrade' header. Looking at source codes I could not find any clue, why the code should be different on different devices.

Am I missing something?

Responding to ping event

Documentation doesn't explain how to respond to ping event on server side.
ws.pong() and ws.send('pong) didn't work.

Header Error => Connection closed before full header was received.

How to fix the error?

I have been used The Library => web_socket_channel: ^1.0.12 (Library Link)

Error Output

WebSocketChannelException: WebSocketChannelException: HttpException: Connection closed before full header was received, uri = http://192.168.1.106

My Socket Code

WebSocketChannel channel = **IOWebSocketChannel.connect("ws://192.168.1.106:80");**

channel.stream.listen(
      (data) {
        print("Socket: data => " + data.toString());
      },
      onError: (error) {
        print("Socket: error => " + error.toString());
      },
      onDone: () {
        print("Socket: done");
      },
    );

This way I am sending a message.

channel.sink.add(/*data*/);

Where is my mistake?

flutter does not recognize packages's imports

After adding web_socket_channel: ^1.0.12 to the pubspec.yaml and flutter packages get, flutter
does not recognize the imports and shows me the following message after hovering on the imports :

Target of URI doesn't exist: 'package:web_socket_channel/io.dart'.
Target of URI doesn't exist: 'package:web_socket_channel/web_socket_channel.dart'.

Write to a dead socket fails only after ~4 minute on iOS

Scenario is simple:

  1. prepare iOS - I use wifi connection to internet and mobile connection is off
  2. use code - it almost from flutter docs + some logs https://github.com/nailgilaziev/ws_change_network_reaction/blob/issue_dead_socket_time/lib/main.dart
  3. run and it must connect to echo server
  4. write "online" and press send - see reaction in logs - all good
  5. switch off wifi on iOS
  6. write "offline" and press send - and... wait reaction in logs...

...wait around 4 minute for detecting that connection is failed. It's too long!!!
Writing to a dead socket connection should not fail over 4 min!

Logs that you see when run this scenario:

flutter: time 2019-06-27 21:21:02.985554
flutter: connection state ConnectionState.waiting
flutter: data null
flutter: error null
flutter:
flutter: time 2019-06-27 21:21:11.949830
flutter: send pressed with payload: online
flutter:
flutter: time 2019-06-27 21:21:12.368631
flutter: connection state ConnectionState.active
flutter: data online
flutter: error null
flutter:
//-------------HERE WIFI IS SWITCHED OFF -------------
flutter: time 2019-06-27 21:21:21.075945
flutter: send pressed with payload: offline
flutter:
flutter: time 2019-06-27 21:25:22.155111
flutter: connection state ConnectionState.done
flutter: data online
flutter: error null

at ~21:21:21 wifi is switched off
at =21:25:22 done event emitted

ps.
Switching off wifi is not an only one case. You can use apple Network link conditioner tool with 100% loss profile to emulate similar (but not the same) situation. For user perspective is the same: Done event occur after ~ 4 min. But it's not the same because in TCP layer things looks different. By switching off wifi OS sends [FIN,ACK] packet to server. By setting 100% profile nothing send to server.

On android behaviour different:

  • switching off wifi cause emitting momentally ConnectionState.done before we can write msg
  • with 100% profile behaviour like in iOS, but it fails faster. almost a 2 min

web_socket_channel: ^1.0.13
Flutter 1.5.4-hotfix.2 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7a4c33425d (8 weeks ago) • 2019-04-29 11:05:24 -0700
Engine • revision 52c7a1e849
Tools • Dart 2.3.0 (build 2.3.0-dev.0.5 a1668566e5)
MacOS mojave 10.14.5 (18F203

Does sink have listen() method?

In README.md, IOWebSocketChannel part has following sample code:

channel.sink.add("connected!");
  channel.sink.listen((message) {
    // ...
  });

But it seems that only stream can be listened.
Besides,when I am using

widget.channel.stream.listen((message) {
      print(message);
 });

I got nothing fired... Any help is appreciated!

Provide concrete example of multiplatform websocket

I have not been able to implement a multiplatform websocket with this package. I see no code examples to assist in the process. The only thing I can figure is that we're supposed to create a platform specific socket channel and pass it to WebSocketChannel.

It's basically gone like this so far:

  1. Oh hey, I'm going to use web_socket_channel it's multiplatform!
  2. What is a StreamChannel?
  3. Okay, import package:web_socket_channel/io.dart...
  4. Now I need a WebSocket?
  5. Okay, import dart:io....
  6. Wait, WebSocket is abstract? Okay, lets implement.... 48 methods?!?!?!

Please give us some breadcrumbs.

Weird sentence in readme

It's strongly recommended that users import this library should be imported with the prefix status.

Would send a PR but I'm just on my phone.

Conditional platform imports

The current package doesn't work with Flutter Web and I get the following error :

transitive libraries have sdk dependencies that not supported on this platform:

web_socket_channel|lib/io.dart

Conditional imports (like implemented in the http's client) would fix the error I guess.

web_socket_channel breaks when using crypto 1.0.0

When using web_socket_channel 1.0.1 with crypto 1.0.0, I get the following error:

No static getter 'BASE64' declared in class 'WebSocketChannel'.

The same error can be seen when running unit tests for this repo:

web_socket_channel $ git checkout 1.0.1
web_socket_channel $ pub get
Resolving dependencies... (4.3s)
+ analyzer 0.27.2 (0.27.3-alpha.4 available)
+ args 0.13.4
+ async 1.9.0
+ barback 0.15.2+7
+ boolean_selector 1.0.0
+ charcode 1.1.0
+ collection 1.4.1
+ convert 1.0.1
+ crypto 1.0.0
+ csslib 0.12.2
+ glob 1.1.1
+ html 0.12.2+1
+ http_multi_server 2.0.0
+ http_parser 2.2.1
+ logging 0.11.2
+ matcher 0.12.0+2
+ mime 0.9.3
+ package_config 0.1.3
+ path 1.3.9
+ plugin 0.1.0
+ pool 1.2.1
+ pub_semver 1.2.3
+ shelf 0.6.5
+ shelf_static 0.2.3+3
+ shelf_web_socket 0.2.0
+ source_map_stack_trace 1.0.4
+ source_maps 0.10.1+1
+ source_span 1.2.2
+ stack_trace 1.6.0 (1.6.4 available)
+ stream_channel 1.3.1
+ string_scanner 0.1.4+1
+ test 0.12.13
+ typed_data 1.1.2
+ utf 0.9.0+3
+ watcher 0.9.7
+ yaml 2.1.8
Downloading crypto 1.0.0...
Changed 36 dependencies!
web_socket_channel $ pub run test
00:00 +4 -1: test/web_socket_test.dart: using WebSocketChannel a server can communicate with a WebSocket client
  No static getter 'BASE64' declared in class 'WebSocketChannel'.

  NoSuchMethodError: method not found: 'BASE64'
  Receiver: Type: class 'WebSocketChannel'
  Arguments: [...]
  dart:core                                          NoSuchMethodError._throwNew
  package:web_socket_channel/src/channel.dart 67:12  WebSocketChannel.signKey
  test/web_socket_test.dart 66:16                    main.<fn>.<fn>.<async>.<fn>.<async>
  ===== asynchronous gap ===========================
  dart:async                                         _Completer.completeError
  test/web_socket_test.dart 78:8                     main.<fn>.<fn>.<async>.<fn>.<async>
  ===== asynchronous gap ===========================
  dart:io                                            _HttpServer.listen
  test/web_socket_test.dart 59:14                    main.<fn>.<fn>.<async>
  ===== asynchronous gap ===========================
  dart:async                                         _asyncThenWrapperHelper
  test/web_socket_test.dart                          main.<fn>.<fn>

00:00 +5 -1: Some tests failed.

How to differentiate connecting and connected states?

First snapshot that StreamBuilder receives is ConnectionState.waiting
This happens when connecting started and in progress.

after connection is established we do not receive any new snapshots. This is undetermined state.
used this code https://flutter.io/cookbook/networking/web-sockets/
print lines added to track snapshots

new StreamBuilder(
  stream: widget.channel.stream,
  builder: (context, snapshot) {
    print("connection state ${snapshot.connectionState}");
    print("data ${snapshot.data}");
    print("error ${snapshot.error}");
    return new Padding(
      padding: const EdgeInsets.symmetric(vertical: 24.0),
      child: new Text(snapshot.hasData ? '${snapshot.data}' : ''),
    );
  },

in logs you see only

I/flutter ( 7150): connection state ConnectionState.waiting
I/flutter ( 7150): data null
I/flutter ( 7150): error null

If connection successful - last snapshot is ConnectionState.waiting
If connection not successful and will die in future (ConnectionTimeout around 2 min) - now you see ConnectionState.waiting and can't decide what to do.

snapshot will be active only when server sends some data to client.

Using IOWebSocketChannel stream inside StreamBuilder causes its closing

Such code causes immediate stream closing (the server reports) without any exceptions and messages:

serverChannel = IOWebSocketChannel.connect('ws://localhost:1234');
...

StreamBuilder(
                  stream: serverChannel.stream,
                  builder: (context, snapshot) => snapshot.data == null ? 
                    CircularProgressIndicator(): 
...

Without such using, serverChannel continues to work.

how to use proxy?

how to use proxy?
such as wss://api.huobi.pro/ws can't connect in china,we must use proxy

Android Studio Updated and now My wroking websocket not working

E/flutter (32734): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: WebSocketChannelException: WebSocketChannelException: SocketException: OS Error: No route to host, errno = 113, address = 192.168.0.49, port = 50777
E/flutter (32734): #0 new IOWebSocketChannel._withoutSocket. (package:web_socket_channel/io.dart:83:24)
E/flutter (32734): #1 _invokeErrorHandler (dart:async/async_error.dart:17:29)
E/flutter (32734): #2 _HandleErrorStream._handleError (dart:async/stream_pipe.dart:286:9)
E/flutter (32734): #3 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:168:13)
E/flutter (32734): #4 _rootRunBinary (dart:async/zone.dart:1144:38)
E/flutter (32734): #5 _CustomZone.runBinary (dart:async/zone.dart:1037:19)
E/flutter (32734): #6 _CustomZone.runBinaryGuarded (dart:async/zone.dart:939:7)
E/flutter (32734): #7 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:355:15)
E/flutter (32734): #8 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:373:16)
E/flutter (32734): #9 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:272:7)
E/flutter (32734): #10 _SyncStreamController._sendError (dart:async/stream_controller.dart:768:19)
E/flutter (32734): #11 _StreamController._addError (dart:async/stream_controller.dart:648:7)
E/flutter (32734): #12 _rootRunBinary (dart:async/zone.dart:1144:38)
E/flutter (32734): #13 _CustomZone.runBinary (dart:async/zone.dart:1037:19)
E/flutter (32734): #14 _CustomZone.runBinaryGuarded (dart:async/zone.dart:939:7)
E/flutter (32734): #15 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:355:15)
E/flutter (32734): #16 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:373:16)
E/flutter (32734): #17 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:272:7)
E/flutter (32734): #18 _SyncStreamController._sendError (dart:async/stream_controller.dart:768:19)
E/flutter (32734): #19 _StreamController._addError (dart:async/stream_controller.dart:648:7)
E/flutter (32734): #20 new Stream.fromFuture. (dart:async/stream.dart:117:18)
E/flutter (32734): #21 _rootRunBinary (dart:async/zone.dart:1144:38)
E/flutter (32734): #22 _CustomZone.runBinary (dart:async/zone.dart:1037:19)
E/flutter (32734): #23 _FutureListener.handleError (dart:async/future_impl.dart:140:20)
E/flutter (32734): #24 Future._propagateToListeners.handleError (dart:async/future_impl.dart:651:47)
E/flutter (32734): #25 Future._propagateToListeners (dart:async/future_impl.dart:672:24)
E/flutter (32734): #26 Future._completeError (dart:async/future_impl.dart:491:5)
E/flutter (32734): #27 Future._asyncCompleteError. (dart:async/future_impl.dart:539:7)
E/flutter (32734): #28 _rootRun (dart:async/zone.dart:1124:13)
E/flutter (32734): #29 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (32734): #30 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter (32734): #31 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:963:23)
E/flutter (32734): #32 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter (32734): #33 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)

Does it support angulardart? If yes, why no WEB tag in pub repo?

In the pub repo, it shows no WEB tag. But it has HtmlWebSocketChannel class. Does it mean it supports angulardart? Thanks.

Screen Shot 2019-03-26 at 14 41 06

Btw, I don't know why it removes headers argument from .connect method from HtmlWebSocketChannel. How to add headers in HtmlWebSocketChannel then?

Add a WebSocketChannel.ready field

Because IOWebSocketChannel.connect() and HtmlWebSocketChannel.connect() are synchronous, there's no way for a caller to know when the connection has actually completed and the web sockets are ready to use. We should add a Future ready getter that completes when the connection is established, or throws an error if it fails. This error should not be top-leveled if it's uncaught, since it will also be sent through the stream itself and some callers may only listen on that.

See #21 and flutter/flutter#18204.

does not work with actix_web

I tried to use a websocket connection to handle the communication between my webserver (written in Rust with actix_web) and my flutter application. Unfortunately it does not work and i really don't know why.

If i try to connect to my server with IOWebSocketChannel.connect it looks like everything is fine. I can listen for messages and send messages and no error is occurring in this process. But on the server side i can see that there is an incoming connection but is immediately closed. This is not reflected on the flutter side nor do i really have any API on the flutter websocket surface to investigate this further.

I also wrote a test server in python that is working with flutter. One could think that the problem now clearly is on the Rust/actix_web side but i also wrote a test client in python and js (a simple webpage) that is running without problem with the Rust/actix_web server and my current Rust application also using this websocket server for communication.

I have created a repository with all the minimal examples. All are just "echo" servers (adjust the ip for your needs) and i also used "ws://echo.websocket.org" in all clients as a third option. Every combination between clients and servers work except Flutter + actix_web.

i also opened an issue for actix_web

Seems incompatible with SDK 1.24 (latest stable)

Hi,

I've set ^1.0.7 in my pubspec dependencies, but when I pub get after removing lock and .packages, I get:

Package web_socket_channel has no versions that match >=1.0.7 <2.0.0

According to mediator:

❯ mediator
✓ No dependency conflicts found! You should be good to go.
Done at 2018-03-16 13:33:38.389067.

I am using SDK 1.24.3 on OS X 10.13.3.

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.