'WebSocketException: Connection to 'http://localhost:1234/ws#' was not upgraded to websocket. Unable to connect to Flutter/Dart VM

Description

I am trying to run a flutter web server and connect to the Dart VM programmatically using the vm_service library. The web server is started successfully but when I try to listen to the socket, I receive the following error:

Unhandled exception: WebSocketException: Connection to 'http://localhost:1234/ws#' was not upgraded to websocket

My code is based on the vm_service library example in the link below where the developers start a Dart VM and connect to it.

https://github.com/dart-lang/sdk/blob/master/pkg/vm_service/example/vm_service_tester.dart


Steps to reproduce

The origin of the error is the following line:

serviceClient = await vmServiceConnect(host, port, log: new StdoutLog());

The complete code is the following:


library service_tester;
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:pedantic/pedantic.dart';
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';
// import 'package:test/test.dart';

final String host = 'localhost';
final int port = 1234;
VmService serviceClient;

void main() async {
  Directory current = Directory.current;
  String sdk = path.dirname(path.dirname(Platform.resolvedExecutable));
  String fsdk = path.dirname(path.dirname(Platform.resolvedExecutable));
  // var flutterSDK = new Directory('C:/flutter/bin');  //FOR WINDOWS
  var flutterSDK = new Directory('/opt/flutter/bin');   //FOR LINUX

  print('Using sdk at ${sdk}');
  print('Directory ${current.path}');
  print('Directory ${flutterSDK.path}/flutter');

  var commands = ["run", "--target=lib/main.dart", "-d", "web", '--web-port=${port}' ];
  print('Running command: flutter ${commands.join(" ")}');
  Process process = await Process.start('flutter', commands , runInShell: true);

  print('dart process started: ${process.pid}');
  process.exitCode.then((code) => print('vm exited: ${code}'));
  process.stdout.transform(utf8.decoder).listen((v)=>print('STDOUT: $v'));
  process.stderr.transform(utf8.decoder).listen((v)=>print('STDERR: $v'));

  await new Future.delayed(new Duration(milliseconds: 1 * 60 * 1000));
  print('\n\nConnecting to ${host}:${port}\n\n');
  serviceClient = await vmServiceConnect(host, port, log: new StdoutLog());
  print('\n\nSocket connected to ${host}:${port}\n\n');
  // serviceClient.onSend.listen((str) => print('--> ${str}'));

  // var checkResponseJsonCompatibility = true;
  // serviceClient.onReceive.listen((str) =>print('<-- ${str}'));
  // serviceClient.onIsolateEvent.listen((e) => print('onIsolateEvent: ${e}'));
  // serviceClient.onDebugEvent.listen((e) => print('onDebugEvent: ${e}'));
  // serviceClient.onGCEvent.listen((e) => print('onGCEvent: ${e}'));
  // serviceClient.onStdoutEvent.listen((e) => print('onStdoutEvent: ${e}'));
  // serviceClient.onStderrEvent.listen((e) => print('onStderrEvent: ${e}'));

  // unawaited(serviceClient.streamListen(EventStreams.kIsolate));
  // unawaited(serviceClient.streamListen(EventStreams.kDebug));
  // unawaited(serviceClient.streamListen(EventStreams.kStdout));

  VM vm = await serviceClient.getVM();
  print('hostCPU=${vm.hostCPU}');
  print(await serviceClient.getVersion());

}

class StdoutLog extends Log {
  void warning(String message) => print(message);

  void severe(String message) => print(message);
}

My pubspec.yaml file is as follows:

name: demo
description: A new Flutter project.
version: 1.0.0+1
environment:
  sdk: ">=2.1.0 <3.0.0"
dependencies:
  flutter:
    sdk: flutter
  vm_service: ^2.1.1
  path: ^1.6.4
  pedantic: ^1.8.0+1
  # test: ^1.9.4
  cupertino_icons: ^0.1.2
dev_dependencies:
  flutter_test:
    sdk: flutter
flutter:

The logs from flutter doctor -v are the following:

[✓] Flutter (Channel master, v1.12.5-pre.27, on Linux, locale en_US.UTF-8)
    • Flutter version 1.12.5-pre.27 at /opt/flutter
    • Framework revision 29ab6b549a (8 hours ago), 2019-11-19 11:29:35 -0800
    • Engine revision ecb32952ff
    • Dart version 2.7.0

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /opt/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • ANDROID_HOME = /opt/sdk
    • Java binary at: /usr/local/openjdk-8/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_232-b09)
    • All Android licenses accepted.

[✗] Chrome - develop for the web (Cannot find chrome executable at google-chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/setup/#android-setup for detailed instructions).

[✓] Connected device (1 available)
    • Web Server • web-server • web-javascript • Flutter Tools

! Doctor found issues in 2 categories.

Error Logs

Running "flutter pub get" in project...                             2.8s
Using sdk at /usr/lib/dart
Directory /project
Directory /opt/flutter/bin/flutter
Running command: flutter run --target=lib/main.dart -d web --web-port=1234
dart process started: 56
STDOUT: Downloading Web SDK...
STDOUT:     3.5s
STDOUT:

STDOUT: Launching lib/main.dart on Web Server in debug mode...
Building application for the web...
STDOUT:    31.9s
lib/main.dart is being served at http://localhost:1234/

Warning: Flutter's support for web development is not stable yet and hasn't
been thoroughly tested in production environments.
For more information see https://flutter.dev/web


STDOUT: 🔥  To hot restart changes while running, press "r". To hot restart (and refresh the browser), press "R".
For a more detailed help message, press "h". To quit, press "q".



Connecting to localhost:1234


Unhandled exception:
WebSocketException: Connection to 'http://localhost:1234/ws#' was not upgraded to websocket
#0      _WebSocketImpl.connect.<anonymous closure>.error (dart:_http/websocket_impl.dart:1052:9)
#1      _WebSocketImpl.connect.<anonymous closure> (dart:_http/websocket_impl.dart:1061:14)
#2      _RootZone.runUnary (dart:async/zone.dart:1379:54)
#3      _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#4      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#5      Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#6      Future._completeWithValue (dart:async/future_impl.dart:522:5)
#7      Future.wait.<anonymous closure> (dart:async/future.dart:400:22)
#8      _RootZone.runUnary (dart:async/zone.dart:1379:54)
#9      _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#10     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#11     Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#12     Future._completeWithValue (dart:async/future_impl.dart:522:5)
#13     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:552:7)
#14     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#15     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#16     _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:116:13)
#17     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:173:5)



Solution 1:[1]

It seems that there is a bug filed related to your question. The bug is still open and yet to be checked by the Dart/Flutter team.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MαπμQμαπkγVπ.0