My server registers the request from the client as several requests

153 views Asked by At

I made a simple WebSocket server using Dart in conjunction with a Flutter client app. When running the client app, the server registers the connection as several requests for some reason. I searched for a while but could not figure out why this is. What might be causing this?

Server code:

import 'dart:io' show HttpServer, HttpRequest, WebSocket, WebSocketTransformer;

void main() {
  var sockets = <WebSocket>[];
  var i = 0;

  HttpServer.bind('localhost', 8080).then((server) {
    print('[+]WebSocket listening at -- ws://localhost:8080/');
    server.listen((HttpRequest request) {
      print('request made');

      WebSocketTransformer.upgrade(request).then((WebSocket ws) {
        sockets.add(ws);
        print('added a socket to the list');
        ws.listen(
          (data) {
            print(data);
            for(var socket in sockets) {
              socket.add('a msg back from the server: $i');
              print('msg sent to the client');
            }
            i++;
          },
          onDone: () => print('[+]Done :)'),
          onError: (err) => print('[!]Error -- ${err.toString()}'),
          cancelOnError: true
        );
      }, onError: (err) => print('[!]Error -- ${err.toString()}'));

    }, onError: (err) => print('[!]Error -- ${err.toString()}'));
  }, onError: (err) => print('[!]Error -- ${err.toString()}'));
}

Client code:

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class ChangingText extends StatefulWidget {
  final _channel = WebSocketChannel.connect(
    Uri.parse('ws://localhost:8080/')
  );

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

class _ChangingTextState extends State<ChangingText> {
  String _text = '';
  WebSocketChannel _channel = WebSocketChannel.connect(
    Uri.parse('ws://localhost:8080/')
  );

  _ChangingTextState() {
    _text = 'press me';
    _channel.stream.listen((data){
      setState(() {_text = data;});
      print(data);
    });
  }

  @override
  Widget build(BuildContext context) {

    return Column(children: [
      ElevatedButton(
        child: Text(_text),
        onPressed: (){widget._channel.sink.add("msg from the flutter client!");},
      ),
    ]);
  }
}

class App extends StatelessWidget {
  const App({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body:
      ChangingText()
    ));
  }
}

void main() {
  runApp(App());
}

Thanks in advance for the help!

1

There are 1 answers

0
dumazy On

Putting the previous comment here to close this question:

Looks like you're connecting twice. In the ChangingText widget and in _ChangingTextState