패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.3.4

data_connection_checker

지정된 주소 목록에 각각 개별 포트와 타임아웃을 사용하여 소켓을 열어 인터넷 연결 여부를 확인하는 순수한 Dart 라이브러리입니다. 편의를 위해 기본값이 제공됩니다.

30일 다운로드
2.2천
좋아요
423
Pub 점수
30

패키지 설치

flutter pub add data_connection_checker

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

구성 가능한 주소 목록에 대해 각각 사용자 지정 포트와 타임아웃을 설정하여 소켓을 열려는 시도를 통해 인터넷 연결 상태를 판단하는 순수 Dart 라이브러리입니다. 빠른 설정을 위해 기본 설정을 제공하면서도 세밀한 제어가 가능합니다. 플랫폼 고유의 API에 의존하지 않고 신뢰할 수 있는 네트워크 상태 감지를 필요로 하는 앱에 적합합니다. 비동기적으로 작동하며 가볍기 때문에 Flutter 앱에서 실시간 연결 모니터링에 적합합니다.

사용 사례

  • API 호출 전 인터넷 연결 여부 확인
  • 백그라운드 작업에서 네트워크 상태 모니터링
  • 데이터 동기화 전 연결 검증
  • 오프라인 모드 로직 구현
  • 연결 상태에 대한 사용자 피드백 제공

주요 기능

  • 소켓 기반 연결 확인
  • 사용자 정의 가능한 호스트 주소 및 포트
  • 사용자 정의 가능한 타임아웃 설정
  • 사용 편의를 위한 기본 구성
  • 콜백을 사용한 비동기 작업

적합한 대상

  • 강력한 네트워크 감지가 필요한 플러터 앱
  • 자주 네트워크 요청을 하는 앱
  • 크로스 플랫폼 일관성을 찾는 개발자
  • 연결 테스트에 정밀한 제어가 필요한 응용 프로그램
  • 플랫폼 고유 코드를 피하는 프로젝트

고려 사항

  • 정상적으로 작동하려면 인터넷 연결이 필요합니다
  • 일시적인 네트워크 문제 발생 시 거짓 음성 결과를 유발할 수 있습니다
  • 소켓 연결을 넘어서 실제 인터넷 도달 가능성을 검증하지 않습니다
  • TCP 연결 확인에 제한됨
  • 내장된 재시도 메커니즘이 없음

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

data_connection_checker

Pub

A pure Dart utility library that checks for an internet connection by opening a socket to a list of specified addresses, each with individual port and timeout. Defaults are provided for convenience.

Note that this plugin is in beta and may still have a few issues. Feedback is welcome.

Table of contents

Description

Checks for an internet (data) connection, by opening a socket to a list of addresses.

The defaults of the plugin should be sufficient to reliably determine if the device is currently connected to the global network, e.i. has access to the Internet.

Note that you should not be using the current network status for deciding whether you can reliably make a network connection. Always guard your app code against timeouts and errors that might come from the network layer.

Quick start

DataConnectionChecker() is actually a Singleton. Calling DataConnectionChecker() is guaranteed to always return the same instance.

You can supply a new list to DataConnectionChecker().addresses if you need to check different destinations, ports and timeouts. Also, each address can have its own port and timeout. See InternetAddressCheckOptions in the docs for more info.

First you need to install it (this is the preferred way)

Then you can start using the library:

bool result = await DataConnectionChecker().hasConnection;
if(result == true) {
  print('YAY! Free cute dog pics!');
} else {
  print('No internet :( Reason:');
  print(DataConnectionChecker().lastTryResults);
}

Purpose

The reason this package exists is that connectivity package cannot reliably determine if a data connection is actually available. More info on its page here: https://pub.dev/packages/connectivity

More info on the issue in general:

You can use this package in combination with connectivity in the following way:

var isDeviceConnected = false;

var subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
  if(result != ConnectivityResult.none) {
    isDeviceConnected = await DataConnectionChecker().hasConnection;
  }
});

Note: remember to properly cancel the subscription when it's no longer needed. See connectivity package docs for more info.

How it works

All addresses are pinged simultaneously. On successful result (socket connection to address/port succeeds) a true boolean is pushed to a list, on failure (usually on timeout, default 10 sec) a false boolean is pushed to the same list.

When all the requests complete with either success or failure, a check is made to see if the list contains at least one true boolean. If it does, then an external address is available, so we have data connection. If all the values in this list are false, then we have no connection to the outside world of cute cat and dog pictures, so hasConnection also returns false too.

This all happens at the same time for all addresses, so the maximum waiting time is the address with the highest specified timeout, in case it's unreachable.

I believe this is a reliable and fast method to check if a data connection is available to a device, but I may be wrong. I suggest you open an issue on the Github repository page if you have a better way of.

Defaults

The defaults are based on data collected from https://perfops.net/, https://www.dnsperf.com/#!dns-resolvers

Here's some more info about the defaults:

DEFAULT_ADDRESSES

... includes the top 3 globally available free DNS resolvers.

Address Provider Info
1.1.1.1 CloudFlare https://1.1.1.1
1.0.0.1 CloudFlare https://1.1.1.1
8.8.8.8 Google https://developers.google.com/speed/public-dns/
8.8.4.4 Google https://developers.google.com/speed/public-dns/
208.67.222.222 OpenDNS https://use.opendns.com/
208.67.220.220 OpenDNS https://use.opendns.com/
static final List<AddressCheckOptions> DEFAULT_ADDRESSES = List.unmodifiable([
  AddressCheckOptions(
    InternetAddress('1.1.1.1'),
    port: DEFAULT_PORT,
    timeout: DEFAULT_TIMEOUT,
  ),
  AddressCheckOptions(
    InternetAddress('8.8.4.4'),
    port: DEFAULT_PORT,
    timeout: DEFAULT_TIMEOUT,
  ),
  AddressCheckOptions(
    InternetAddress('208.67.222.222'),
    port: DEFAULT_PORT,
    timeout: DEFAULT_TIMEOUT,
  ),
]);
DEFAULT_PORT

... is 53.

A DNS server listens for requests on port 53 (both UDP and TCP). So all DNS requests are sent to port 53 ...

More info:

static const int DEFAULT_PORT = 53;
DEFAULT_TIMEOUT

... is 10 seconds.

static const Duration DEFAULT_TIMEOUT = Duration(seconds: 10);
DEFAULT_INTERVAL

... is 10 seconds. Interval is the time between automatic checks. Automatic checks start if there's a listener attached to onStatusChange, thus remember to cancel unneeded subscriptions.

checkInterval (which controls how often a check is made) defaults to this value. You can change it if you need to perform checks more often or otherwise.

static const Duration DEFAULT_INTERVAL = const Duration(seconds: 10);
...
Duration checkInterval = DEFAULT_INTERVAL;

Usage

Example:

import 'package:data_connection_checker/data_connection_checker.dart';

main() async {
  // Simple check to see if we have internet
  print("The statement 'this machine is connected to the Internet' is: ");
  print(await DataConnectionChecker().hasConnection);
  // returns a bool

  // We can also get an enum value instead of a bool
  print("Current status: ${await DataConnectionChecker().connectionStatus}");
  // prints either DataConnectionStatus.connected
  // or DataConnectionStatus.disconnected

  // This returns the last results from the last call
  // to either hasConnection or connectionStatus
  print("Last results: ${DataConnectionChecker().lastTryResults}");

  // actively listen for status updates
  // this will cause DataConnectionChecker to check periodically
  // with the interval specified in DataConnectionChecker().checkInterval
  // until listener.cancel() is called
  var listener = DataConnectionChecker().onStatusChange.listen((status) {
    switch (status) {
      case DataConnectionStatus.connected:
        print('Data connection is available.');
        break;
      case DataConnectionStatus.disconnected:
        print('You are disconnected from the internet.');
        break;
    }
  });

  // close listener after 30 seconds, so the program doesn't run forever
  await Future.delayed(Duration(seconds: 30));
  await listener.cancel();
}

Note: Remember to dispose of any listeners, when they're not needed to prevent memory leaks, e.g. in a StatefulWidget's dispose() method:

...
@override
void dispose() {
  listener.cancel();
  super.dispose();
}
...

See example folder for more examples.

License

MIT

Copyright 2019 Kristiyan Mitev and Spirit Navigator

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Features and bugs

Please file feature requests and bugs at the issue tracker.

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트