Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging web-socket issues in Flutter

I'm wanting to know how to debug web-socket connection issues in Flutter.

Taking the most simple possible example from the Flutter docs themselves :
https://flutter.dev/docs/cookbook/networking/web-sockets#complete-example

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'WebSocket Demo';
    return MaterialApp(
      title: title,
      home: MyHomePage(
        title: title,
        channel: IOWebSocketChannel.connect('ws://echo.websocket.org'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  final WebSocketChannel channel;

  MyHomePage({Key key, @required this.title, @required this.channel})
      : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = TextEditingController();

  @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: <Widget>[
            Form(
              child: TextFormField(
                controller: _controller,
                decoration: InputDecoration(labelText: 'Send a message'),
              ),
            ),
            StreamBuilder(
              stream: widget.channel.stream,
              builder: (context, snapshot) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 24.0),
                  child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
                );
              },
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'Send message',
        child: Icon(Icons.send),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _sendMessage() {
    if (_controller.text.isNotEmpty) {
      widget.channel.sink.add(_controller.text);
    }
  }

  @override
  void dispose() {
    widget.channel.sink.close();
    super.dispose();
  }
}

This code works without a hitch.

But if I put in total gibberish for the socket server, (eg. IOWebSocketChannel.connect('ws://total-gibberish-clearly-not-a-ws-server')) the code still runs without complaint. Obviously the message sent doesn't echo (which is what the 'ws://echo.websocket.org' server does), but there is no error message, no indication that this isn't a web-socket server.

My actual situation is that I DO have a REAL web-socket server and I'm having trouble connecting to it, but I don't know what the issue is.

How do I detect and show the error details of a failed web-socket connection in Flutter?

like image 527
Flutter Learner Avatar asked Jun 01 '26 07:06

Flutter Learner


1 Answers

I'm using a different (more low level) approach in this sample socket client : https://github.com/krisrandall/really_simple_socket_client
but it includes error detection.

This is all of the code :

import 'dart:io';

WebSocket _webSocket;

String socketServerUrl = 'ws://echo.websocket.org/';
//String socketServerUrl = 'ws://echo.FAILS.org/';

void main() {

  Future<WebSocket> futureWebSocket = WebSocket.connect(socketServerUrl);
  futureWebSocket.then((WebSocket ws) {
    _webSocket = ws;
    print(_webSocket.readyState);

    _webSocket.listen(
        (d) { print(d); },
        onError: (e) { print("error"); print(e); }, 
        onDone: () => print("done")
    );

    // send message
    _webSocket.add('hello websocket world');

  });


}
like image 154
kris Avatar answered Jun 03 '26 23:06

kris