Graphql-flutter: WebSocketException: Connection not upgraded to websocket

Created on 30 Nov 2019  路  12Comments  路  Source: zino-app/graphql-flutter

Good day, please any idea on how to resolve this

/flutter (31920): Connecting to websocket: ws://192.168.43.95:8080/graphql...
I/flutter (31920): There was an error causing connection lost: WebSocketException: Connection to 'http://192.168.43.95:8080/graphql#' was not upgraded to websocket
I/flutter (31920): Disconnected from websocket.
I/flutter (31920): Scheduling to connect in 5 seconds...
I/flutter (31920): Connecting to websocket: ws://192.168.43.95:8080/graphql...
I/flutter (31920): There was an error causing connection lost: WebSocketException: Connection to 'http://192.168.43.95:8080/graphql#' was not upgraded to websocket
I/flutter (31920): Disconnected from websocket.

Tested on
^2.1.1-beta.4
^2.1.0
^2.0.1

http request work flawless but websocket is giving me headache. any one pls.
here is my code

const String YOUR_PERSONAL_ACCESS_TOKEN =
    'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

const bool ENABLE_WEBSOCKETS = true;

class Principal extends StatelessWidget {
  const Principal() : super();

  @override
  Widget build(BuildContext context) {
    final HttpLink httpLink = HttpLink(
      uri: 'http://192.168.43.95:3030/graphql',
    );

    final AuthLink authLink = AuthLink(
      getToken: () async => 'Bearer $YOUR_PERSONAL_ACCESS_TOKEN',
    );

    Link link = authLink.concat(httpLink);
    if (ENABLE_WEBSOCKETS) {
      final WebSocketLink websocketLink = WebSocketLink(
        url: 'ws://192.168.43.95:3030/graphql',
        config: SocketClientConfig(
            autoReconnect: true, inactivityTimeout: Duration(seconds: 15),
            initPayload: {}  
          ),
      );

      link = link.concat(websocketLink);
    }

    final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(
      GraphQLClient(
        cache: OptimisticCache(
          dataIdFromObject: typenameDataIdFromObject,
        ),
        link: link,
      ),
    );


    return GraphQLProvider(
      client: client,
      child: const CacheProvider(
        child: MyHomePage(title: 'GraphQL Widget'),
      ),
    );

  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key key,
    this.title,
  }) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Person> listPerson = List<Person>();
  QueryMutation queryMutation = QueryMutation();



  @override
  void initState() {
    super.initState();
    //fillList();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Example"),
      ),
      body: Stack(
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width,
            child: Text(
              "Person",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 30.0),
            ),
          ),
          Query(
            options: QueryOptions(
              document: queryMutation.getAll(),
            ), builder: (QueryResult result, {refetch, fetchMore}) {

                if (result.loading) {
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                }

                if (result.hasErrors) {
                  return Text('\nErrors: \n  ' + result.errors.join(',\n  '));
                }

                if (result.data == null && result.errors == null) {
                  return const Text(
                      'Both data and errors are null, this is a known bug after refactoring, you might forget to set Github token');
                }

                // result.data can be either a [List<dynamic>] or a [Map<String, dynamic>]
                final List<LazyCacheMap> repositories = (result.data['Persons'] as List<dynamic>).cast<LazyCacheMap>();

                return  ListView.builder(
                    itemCount: repositories.length,
                    itemBuilder: (BuildContext context, int index) {
                      return ListTile(
                        selected: repositories == null ? false : true,
                        title: Text(
                          repositories[index]['firsName'],
                        ),
                        onTap: () => {},
                      );
                    },
                  );

            },
          ),
            ENABLE_WEBSOCKETS
              ? Subscription<Map<String, dynamic>>(
                    'PERSON_ADDED', queryMutation.testSubscription(), builder: ({
                    bool loading,
                    Map<String, dynamic> payload,
                    dynamic error,
                  }) {
                    if (error != null) {
                      return Text('\nErrors: \n  ' + error.join(',\n  '));
                    }

                    return loading ? const Text('Loading...') : Text(payload.toString());
                  })
              : const Text(''),
        ],
      ),
    );
  }
}


help wanted investigate link outdated

All 12 comments

I am not sure about this, but a WebSocket is upgraded by the server and not the client. It is initialized just like a normal HTTP request and upgraded to WebSocket after the handshake. This seems like an error on the backend and I would suggest trying the to use GraphiQL and see if it works and then report back.

@mainawycliffe Graphql works, tested with postman and my web browser. Its more flutter issue
flutter issue
Another flutter issue.

I can upload my server code on github if you don't mind then test on your side

If I read the issues correctly this could be an issue with the emulator and device settings. It would be helpful if you could upload your server code and when I get some time I will try and test it.

@mainawycliffe here is my server code
FeatherjsGraphql.

thanks

@mainawycliffe any luck with this

Why is # appended to the URI?

My host is ws://192.168.1.159:8080/echo but flutter is failing with WebSocketException: Connection to 'http://192.168.1.159:8080/echo#' was not upgraded where is the # from?

Code:

    final channel = IOWebSocketChannel.connect('ws://192.168.1.159:8080/echo',
        headers: {'Connection': 'upgrade', 'Upgrade': 'websocket'});
    channel.stream.listen((message) {
      print("message $message");
    });

This is likely resolved on 4.0.0-beta. If someone still has this issue there please comment and I'll reopen

Yes I still have an issue with this

image

All right, I found that the issue is my Nginx proxy server making this error. No wonder ws protocol is changing to http.
image
https://www.nginx.com/blog/websocket-nginx/

Yes we added a condition on the api to check for gql flutter protocol.

@Pinteezy and that solved your issue? So it looks to me like this was both:

  • an issue with flutter that has since been resolved
  • a tricky server-side configuration that can result in a similar error

Is my read correct, or is there something we should be doing differently here? I have not looked deeply

Was this page helpful?
0 / 5 - 0 ratings