简体   繁体   中英

Flutter socket.io connect to nodejs socket.io

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM