Building Flutter app with Socket.io: can't listen to or emit msgs to the socket channel

5,920

Solution 1

You can try out below library. I tried to subscribe to channels and listen to events and it works well.

https://github.com/kakajansh/echo

Solution 2

If you are using Android Studio emulator then use http://10.0.2.2:7000 as URI (change port according to your localhost eg. 3000 or 3001). The above URI helps in getting your actual device (your computer) local host. I have tried this and is successfully working with Adhara_socket_io.

Share:
5,920
Wissa
Author by

Wissa

Passionately coding, enthusiastically building new apps and innovating using Swift and the iOS SDK. It all started when I left my full time job to join a professional training program (ITI) for 9 months where I extensively and intensively learned to utilize more than 30 open-source technologies to develop and build numerous projects. In my pursue to learn and tackle new challenges I participated in many Hackathons working with diverse teams from Europe, Asia, and Africa with different cultural and technical backgrounds. Two things I value the most in my career: to be challenged, to overcome these challenges and the learning journey in between. If you want to get in touch, email me at '[email protected]'

Updated on December 09, 2022

Comments

  • Wissa
    Wissa over 1 year

    I am using adhara socket io with flutter to build a socket app. https://pub.dartlang.org/packages/adhara_socket_io The socket connects successfully but not listening or emitting any data to the events I have. I tested from a web client everything works perfectly.

    This is the example code provided by the library that I'm using:

    import 'package:flutter/material.dart';
    import 'dart:convert';
    import 'package:adhara_socket_io/adhara_socket_io.dart';
    
    void main() => runApp(MyApp());
    
    const String URI = "http://172.25.1.206:6001/";
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      List<String> toPrint = ["trying to conenct"];
      SocketIOManager manager;
      SocketIO socket;
      bool isProbablyConnected = false;
    
      @override
      void initState() {
        super.initState();
        manager = SocketIOManager();
        initSocket();
      }
    
      initSocket() async {
        setState(() => isProbablyConnected = true);
        socket = await manager.createInstance(
          //Socket IO server URI
            URI,
            //Query params - can be used for authentication
            query: {
              "auth": "--SOME AUTH STRING---",
              "info": "new connection from adhara-socketio"
            },
            //Enable or disable platform channel logging
            enableLogging: false
        );
        socket.onConnect((data) {
          pprint("connected...");
          pprint(data);
          sendMessage();
        });
        socket.onConnectError(pprint);
        socket.onConnectTimeout(pprint);
        socket.onError(pprint);
        socket.onDisconnect(pprint);
        socket.on("ExampleEvent", (data) {
          pprint("news");
          pprint(data);
        });
        socket.connect();
      }
    
      disconnect(){
        manager.clearInstance(socket);
        setState(() => isProbablyConnected = false);
      }
    
      sendMessage() {
        if (socket != null) {
          pprint("sending message...");
          socket.emit("ExampleEvent", [
            "Hello world!",
            1908,
            {
              "wonder": "Woman",
              "comics": ["DC", "Marvel"]
            },
            {
              "test": "=!./"
            },
            [
              "I'm glad",
              2019,
              {
                "come back": "Tony",
                "adhara means": ["base", "foundation"]
              },
              {
                "test": "=!./"
              },
            ]
          ]);
          pprint("Message emitted...");
        }
      }
    
      pprint(data) {
        setState(() {
          if (data is Map) {
            data = json.encode(data);
          }
          print(data);
          toPrint.add(data);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
              textTheme: TextTheme(
                title: TextStyle(color: Colors.white),
                headline: TextStyle(color: Colors.white),
                subtitle: TextStyle(color: Colors.white),
                subhead: TextStyle(color: Colors.white),
                body1: TextStyle(color: Colors.white),
                body2: TextStyle(color: Colors.white),
                button: TextStyle(color: Colors.white),
                caption: TextStyle(color: Colors.white),
                overline: TextStyle(color: Colors.white),
                display1: TextStyle(color: Colors.white),
                display2: TextStyle(color: Colors.white),
                display3: TextStyle(color: Colors.white),
                display4: TextStyle(color: Colors.white),
              ),
              buttonTheme: ButtonThemeData(
                  padding: EdgeInsets.symmetric(vertical: 24.0, horizontal: 12.0),
                  disabledColor: Colors.lightBlueAccent.withOpacity(0.5),
                  buttonColor: Colors.lightBlue,
                  splashColor: Colors.cyan
              )
          ),
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Adhara Socket.IO example'),
              backgroundColor: Colors.black,
              elevation: 0.0,
            ),
            body: Container(
              color: Colors.black,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                      child: Center(
                        child: ListView(
                          children: toPrint.map((String _) => Text(_ ?? "")).toList(),
                        ),
                      )),
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.symmetric(horizontal: 8.0),
                        child: RaisedButton(
                          child: Text("Connect"),
                          onPressed: isProbablyConnected?null:initSocket,
                        ),
                      ),
                      Container(
                          margin: EdgeInsets.symmetric(horizontal: 8.0),
                          child: RaisedButton(
                            child: Text("Send Message"),
                            onPressed: isProbablyConnected?sendMessage:null,
                          )
                      ),
                      Container(
                          margin: EdgeInsets.symmetric(horizontal: 8.0),
                          child: RaisedButton(
                            child: Text("Disconnect"),
                            onPressed: isProbablyConnected?disconnect:null,
                          )
                      ),
                    ],
                  ),
                  SizedBox(height: 12.0,)
                ],
              ),
            ),
          ),
        );
      }
    }
    
  • Matthcw
    Matthcw almost 4 years
    +1 This worked... I was using 192.128.43.98:3000 which worked fine for ordinary HTTP requests, but when using websockets, it doesn't work for some reason (Using MacOS, using the Android Emulator in Android Studio)
  • Mitrakov Artem
    Mitrakov Artem almost 3 years
    +1 it works! This code gets the trick for me: final host = Platform.isAndroid ? "10.0.2.2" : "127.0.0.1";