title: Correct way of creating a connection between multiple devices to send and receive data
body: <p>Okay so I'm tired of trying to figure out how to do this. I can't find a tutorial or article or anything that explains how to do it.</p>
  <p>I want to make an app where a device creates a connection and other devices nearby can connect to it. Some good examples of what I want to implement are <strong>Pou</strong> and <strong>XConnectedApps</strong> apps.</p>
  <p><strong>Pou</strong> has some minigames where you can play with your friends near you either by <em>bluetooth</em> or <em>mobile hotspot</em>. One player creates the game (or connection) or opens a room and the other players choose this room from a list that scans the opened rooms.</p>
  <p><strong>XConnectedApps</strong> has 2 apps: <em>Barcode Reader</em> and <em>Universal Clipboard</em>. Both work the same way. You install a small app on your PC which starts a server when run and you install the other apps on the phone. The android app can scan for the servers on the same network and connect to one of them. Once the connection is complete, you can start sending and receiving data.</p>
  <p>I read somewhere that I should start a server using <code>HttpServer</code> and use the <code>http</code> package to connect to it and send requests. So this is what I did:</p>
  <pre class="lang-dart prettyprint-override"><code>class _MyHomePageState extends State&lt;MyHomePage&gt; {
    final TextEditingController _controller = TextEditingController();
  
    late HttpServer _server;
    bool _serverRunning = false;
  
    @override
    void dispose() {
      _controller.dispose();
      _server.close();
      super.dispose();
    }
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Form(
                child: TextFormField(
                  controller: _controller,
                  decoration: const InputDecoration(labelText: 'Send a message'),
                ),
              ),
              const SizedBox(height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  FloatingActionButton(
                    onPressed: _serverRunning ? _stopServer : _startServer,
                    tooltip: _serverRunning ? &quot;Stop Server&quot; : &quot;Start Server&quot;,
                    child: Icon(_serverRunning ? Icons.stop : Icons.play_arrow),
                  ),
                  FloatingActionButton(
                    onPressed: _sendMessage,
                    tooltip: &quot;Send Message&quot;,
                    child: Icon(Icons.send),
                  ),
                ],
              ),
            ],
          ),
        ),
      );
    }
  
    Future&lt;void&gt; _startServer() async {
      final info = NetworkInfo();
      var wifiIP = await info.getWifiIP();
  
      _server = await HttpServer.bind(InternetAddress(wifiIP!), 8080);
      print(&quot;server running on ${_server.address}&quot;);
      setState(() {
        _serverRunning = true;
      });
  
      _server.listen((HttpRequest request) {
        request.response.write(&quot;Hello World!&quot;);
        request.response.close();
      });
    }
  
    Future&lt;void&gt; _stopServer() async {
      await _server.close();
      setState(() {
        _serverRunning = false;
      });
    }
  
    Future&lt;void&gt; _sendMessage() async {
      if (_controller.text.isEmpty) {
        return;
      }
  
      var response = await http.post(
        Uri.parse(&quot;http://192.168.1.10:8080&quot;),
        body: {
          &quot;name&quot;: &quot;User&quot;,
          &quot;data&quot;: _controller.text,
        },
      );
      
      print(&quot;response status: ${response.statusCode}, body: ${response.body}&quot;);
    }
  }
  </code></pre>
  <p>This shows a text field which contains the message that will be sent and 2 buttons: one to start/stop the server and another one to send the message.</p>
  <p>On desktop, I start a server using the same machine's IP address and I was able to access the webpage on any device on the same LAN (just to see if it works) and I was able to see the <code>Hello World!</code> message passed in <code>request.response.write(&quot;Hello World!&quot;)</code> in the body of the <code>listen()</code> function. But what I was not able to do and I don't think if I can do this is to receive the data passed in the body of the <em>POST</em> request at the end of this code. The hardcoded IP is the desktop's IP on the network.</p>
  <p>As you can see, I though I could start a server on my PC and using my Android phone I can send a request to the server's IP address with some data in the body. But I'm not able to access that data on the server side when listening for requests.</p>
  <hr />
  <p>Anyway, I thought of another way to do it, thinking it is easier; using Bluetooth. I found <a href="https://pub.dev/packages/quick_blue" rel="nofollow noreferrer">this</a> package which supports Windows and Android. So I changed my code to this:</p>
  <pre class="lang-dart prettyprint-override"><code>class _HomeScreenState extends State&lt;HomeScreen&gt; {
    final _controller = TextEditingController();
  
    bool _scanRunning = false;
  
    List&lt;String&gt; _infoList = [];
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        body: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            children: [
              TextFormField(
                controller: _controller,
                decoration: const InputDecoration(labelText: 'Send a message'),
              ),
              const SizedBox(height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  FloatingActionButton(
                    onPressed: _scanRunning ? _stopScan : _startScan,
                    tooltip: _scanRunning ? &quot;Stop Scan&quot; : &quot;Start Scan&quot;,
                    child: Icon(_scanRunning ? Icons.stop : Icons.play_arrow),
                  ),
                  FloatingActionButton(
                    onPressed: _sendMessage,
                    tooltip: &quot;Send Message&quot;,
                    child: Icon(Icons.send),
                  ),
                ],
              ),
              const SizedBox(height: 24),
              ..._infoList.map(
                (info) =&gt; Text(info),
              ),
            ],
          ),
        ),
      );
    }
  
    void _addMessage(String message) {
      setState(() {
        _infoList.add(message);
      });
    }
  
    Future&lt;void&gt; _startScan() async {
      bool isAvailable = await QuickBlue.isBluetoothAvailable();
      if (!isAvailable) {
        _addMessage(&quot;Bluetooth not supported on this device&quot;);
      } else {
        _addMessage(&quot;Buetooth is on&quot;);
      }
  
      QuickBlue.startScan();
      _addMessage(&quot;Scanning devices....&quot;);
      setState(() {
        _scanRunning = true;
      });
  
      QuickBlue.scanResultStream.listen((result) {
        String message = &quot;ID: ${result.deviceId}\nName: ${result.name}&quot;;
  
        if (_infoList.contains(message)) {
          setState(() {
            _infoList.removeWhere((element) =&gt; element == message);
          });
        } else {
          _addMessage(message);
        }
      });
    }
  
    void _stopScan() {
      QuickBlue.stopScan();
      _addMessage(&quot;Scan stopped&quot;);
      setState(() {
        _scanRunning = false;
      });
    }
  
    void _sendMessage() {
      
    }
  }
  </code></pre>
  <p>If bluetooth is turned off it shows that it is not available. Not if the device supports bluetooth. I wanted it to show a list of devices that have bluetooth turned ON, similar to the one in bluetooth settings page. If a device has bluetooth turned on, it is shown in the list. Otherwise it is removed.</p>
  <p>Using this code, I had a lot of items in the list blinking, cause they kept being added and removed, I don't know why. The name is shown either blank or some kind of MAC address or something. And the device id always changes each time bluetooth is turned ON and OFF.</p>
  <p>I didn't know how to continue with this code because I don't think I am on the correct path. So I'm asking you guys. Does anyone know how can I do this kind of stuff? I've been struggling with this for many months. Any help would be really appreciated. Thank You for your time!</p>