Flutter socket.io connect to nodejs socket.io

5,970

Use socket_io_client instead adhara_socket_io.

In pubspec.yaml file add package socket_io_client: ^0.9.4 and flutter_simple_dependency_injection: ^1.0.1

You can create Singleton service like code below (to avoid multiple instance of class):

import 'package:socket_io_client/socket_io_client.dart' as IO;
import 'package:tiche_flutter/config.dart';

class SocketService {
  IO.Socket socket;

  createSocketConnection() {
    socket = IO.io(config.socketUrl, <String, dynamic>{
      'transports': ['websocket'],
    });

    this.socket.on("connect", (_) => print('Connected'));
    this.socket.on("disconnect", (_) => print('Disconnected'));
  }
}

Create file dependecy_injection.dart

class DependencyInjection {
  Injector initialise(Injector injector) {
    injector.map<SocketService>((i) => SocketService(), isSingleton: true);
    return injector;
  }
}

Create file app_initializer.dart

import 'package:flutter_simple_dependency_injection/injector.dart';
class AppInitializer {
  initialise(Injector injector) async {}
}

Add to your main.dart

Injector injector;
void main() async {
  DependencyInjection().initialise(Injector.getInjector());
  injector = Injector.getInjector();
  await AppInitializer().initialise(injector);
  runApp(MyApp());
}

You need to run createSocketConnection function to create connection in your dart file. So, in your file, write code:

final SocketService socketService = injector.get<SocketService>();
socketService.createSocketConnection();

If socket connection was created, you will see "Connected" in your terminal

It works for me.

Share:
5,970
Antoni Dobrenov
Author by

Antoni Dobrenov

Updated on December 16, 2022

Comments

  • Antoni Dobrenov
    Antoni Dobrenov over 1 year

    This is my server

    class ChatbotServer {
      private http: Server;
      private io: socketIo.Server;
    
      constructor(app: express.Application, private nluService: NluService, private loggerService: LoggerService) {
        this.http = createServer(app);
        this.io = socketIo(this.http);
    
        this.setupSocketIo();
      }
    
      private setupSocketIo() {
        this.io.on("connection", socket => {
          new ChatSocketConnection(socket, this.nluService, this.loggerService);
        });
      }
    
      listen() {
        this.http.listen(port, () => console.log(`socket.io listening on port ${port}`));
      }
    }
    

    And this is my flutter client

    class MySocketApp extends StatefulWidget {
      @override
      _MySocketAppState createState() => _MySocketAppState();
    }
    
    enum ConnectionStatus { connected, disconnected }
    
    class _MySocketAppState extends State<MySocketApp> {
      SocketIOManager manager = SocketIOManager();
      SocketIO socket;
      var status = ConnectionStatus.disconnected;
    
    
    
      @override
      void initState() {
        super.initState();
        setupSocketConnections();
      }
    
      void disconnectSocketConnections() async {
        await manager.clearInstance(socket);
        status = ConnectionStatus.disconnected;
        print("disconnected");
      }
      void setupSocketConnections() async {
        print("asd");
    
        socket = await manager.createInstance(SocketOptions('http://localhost:3001/'));
        socket.onConnect((data) {
          status = ConnectionStatus.connected;
          print("connected...");
        });
        socket.onConnectError((data) {
          print("Connection Error");
        });
        socket.onConnectTimeout((data) {
          print("Connection Timed Out");
        });
        socket.connect();
      }
    

    I follow a tutorial and the examples in adhara_socket_io pub, but still i can't connect the sockets. I have an web app on react and I don't have any problems with the sockets connection. This means that the server side is okay, so probably I am missing something in the flutter part. If anybody have some clue I will be thankful!

  • Andrew Kovalchuk
    Andrew Kovalchuk over 4 years
    @AntoniDobrenov You are welcome. I am glad to help)
  • Nikhil.Nixel
    Nikhil.Nixel almost 3 years
    Is there any way to send message in private channel [say RoomId] like, 'this.socket.in(roomId).on('message', () {})'? Its possible on nodejs server side. Also did the same with client side but on react side. Curious on how to achieve the same with this library for flutter
  • Admin
    Admin almost 3 years
    Hi, @AndrewKovalchuk, If I want to connect to the socektio url with namespace , how do I do that? where should I provide namespace?