Unexpected websocket requests after my http requests

188

The reason for this is because DevTools (for some reason) are calling normal sockets for WebSocket. I have created an issue about this behavior since it is confusing: https://github.com/flutter/devtools/issues/3033

The "Network" tab contains different kind of events which are combined into the same overview. In this case we are seeing both HTTP and socket events.

The reason you are seeing the HTTP event first, is because the overview is sorted by the time each event is started. For HTTP events, the time is started before a socket is created.

Since HTTP communication are happening using sockets, the Dart VM will try establish a socket connection to the server you are going to communicate with. The creating of this socket are triggering a event to be sent to DevTools about a new socket has been created.

It is this socket you are seeing (wrongly named WebSocket). After this socket has been established, the HttpClient are then using it to communicate with the server using the HTTP protocol.

The reason why you are seeing multiple WebSocket (which are really Socket...) for repeatable calls is because you are creating a new HttpClient object in your loop. Normally, you should reuse the HttpClient since it will automatically keep the socket alive for 15 seconds (default, and can be configured) in case you are going to make another HTTP call against the same server. If you do this, you should only see one WebSocket (but should be Socket) be created in your example.

Share:
188
Osman Aslancan
Author by

Osman Aslancan

Updated on November 27, 2022

Comments

  • Osman Aslancan
    Osman Aslancan over 1 year

    When I make http requests in dart or flutter a websocket request always comes after it. I wondered is it from packages and write a flat dart script but it didn't solve the problem. Here is the script that I wrote.

    import 'dart:io';
    
    main(List<String> args) async {
      while (true) {
        final client = HttpClient();
        await Future.delayed(Duration(seconds: 10));
        final req = await client.getUrl(Uri.parse('https://example.com/'));
        await req.close();
        client.close();
      }
    }
    

    here is the output of my debug

    it may have something with the httpclient because when I force close it websocket requests end instead of pending.

    So question is what is the reason that websocket request happen ?

    Dart Version: 2.12.3 (stable)