connect method

Future<void> connect({
  1. required Future<void> onSocketData(
    1. dynamic data
    ),
  2. required FutureOr<void> onSocketConnection(
    1. SocketConnection socketConnection
    ),
  3. Duration delayDuration = const Duration(milliseconds: 500),
})

Implementation

Future<void> connect({
  required Future<void> Function(dynamic data) onSocketData,
  required FutureOr<void> Function(SocketConnection socketConnection)
      onSocketConnection,
  Duration delayDuration = const Duration(milliseconds: 500),
}) async {
  while (true) {
    await Future.delayed(delayDuration);
    if (isConnect == false) {
      try {
        socket = await WebSocket.connect(
          url,
          protocols: protocols,
          headers: headers,
          compression: compression,
          customClient: customClient,
        );
        socket.pingInterval = pingInterval;
        StreamSubscription scoketListen = socket.listen(
          (event) async {
            await onSocketData(event);
            return;
          },
          onError: (a, b) {
            isConnect = false;
          },
          onDone: () async {
            isConnect = false;

            await onSocketConnection(SocketConnection({
              "@type": "socketConnection",
              "status": SocketConnectionType.disconnect.name,
            }));
            Timer.periodic(pingInterval ?? Duration(seconds: 2),
                (timer) async {
              if (isConnect) {
                timer.cancel();
                return;
              }
              try {
                await connect(
                    onSocketData: onSocketData,
                    onSocketConnection: onSocketConnection,
                    delayDuration: delayDuration);
              } catch (e) {}
            });
          },
          cancelOnError: true,
        );
        isConnect = true;

        await onSocketConnection(SocketConnection({
          "@type": "socketConnection",
          "status": SocketConnectionType.connected.name,
        }));
        return;
      } catch (e) {
        isConnect = false;
        if (e is SocketException) {
          isConnect = false;
        }
        try {
          await socket.done;
          await socket.close();

          await onSocketConnection(SocketConnection({
            "@type": "socketConnection",
            "status": SocketConnectionType.reconnection.name,
          }));
          await connect(
            onSocketData: onSocketData,
            onSocketConnection: onSocketConnection,
            delayDuration: delayDuration,
          );
        } catch (e) {
          await onSocketConnection(SocketConnection({
            "@type": "socketConnection",
            "status": SocketConnectionType.reconnection.name,
          }));
        }
      }
    }
  }
}