티스토리 뷰

목차

    반응형


    출처는 스택오버플로우(stack overflow)입니다.

    Node.js + Electron 활용해서 인터넷 연결을 1초 주기로 확인하는 예제입니다. 실제로 1초는 너무 빠르니 잘 조절해서 사용해 보세요.


    1초 마다 연결되지 않고 연결이 끊어짐을 감지하여 인터넷 연결이 끊겼음을 알려주는 예제 3개인데요. 먼저, internet-available 패키지는 연결 상태를 딱 1번만 알려줘서 주기적인 확인은 불가능하고요. navigator.onLine은 일렉트론 exe 파일과 프레임워크 사이의 연결 상태를 반환하므로 실제 인터넷 연결 상태를 확인하는 건 아닙니다. 그래서 사용하시면 안 됩니다.

    1. let isConnected

    플래그를 추가하여 주기적으로 인터넷 연결 상태를 확인합니다. require("dns")를 추가하고 dns.resolve 함수를 주기적으로 호출해 isConnected 플래그의 값을 변경합니다. node.js, 일렉트론 어디든 추가해도 됩니다.


    const dns = require("dns");
    let isConnected = false;

    function liveCheck() {
      dns.resolve("www.google.com", function(err, addr) {
        if (err) {
          if (isConnected) {
            notifier.notify({
              appName: "com.myapp.id",
              title: "network error",
              message: "disconnected",
              icon: "./facebook.png",
            });
          }
          isConnected = false;
        } else {
          if (isConnected) {
            //connection is still up and running, do nothing
          } else {
            notifier.notify({
              appName: "com.myapp.id",
              title: "connection gained",
              message: "connected",
              icon: "./facebook.png",
            });
          }
          isConnected = true;
        }
      });
    }

    setInterval(function() {
      liveCheck();
    }, 1000);


    인터넷 연결 상태에선 별 반응이 없지만, 연결 끊길 시 1초마다 로그가 찍힙니다.


    2. check-internet-connected

    npm util 중 check-internet-connected를 활용합니다.


    const checkInternetConnected = require('check-internet-connected');

      const config = {
        timeout: 5000, //timeout connecting to each try (default 5000)
        retries: 3,//number of retries to do before failing (default 5)
        domain: 'apple.com'//the domain to check DNS record of
      }

      checkInternetConnected(config)
        .then(() => {
          console.log("Connection available");          
        }).catch((err) => {
          console.log("No connection", err);
        });


    플래그를 사용할 때 보단 소스가 확실히 간소하네요.

    3. window.addEventListener

    electron에 이벤트 리스너를 활용하는 방법입니다.


    function notifyUser (event)
    {
        let myNotification = new Notification
        (
            "com.myapp.id",
            { body: (event.type === 'online') ? "Internet available" : "No internet" }
        ); 
    }
    window.addEventListener ('online', notifyUser, false);
    window.addEventListener ('offline', notifyUser, false);


    위 소스는 html에 추가하면 됩니다.


    이상 일렉트론(electron)과 노드제이에스(Node.js)를 활용할 때, 인터넷 연결 상태를 주기적으로 확인하는 3가지 방법이었습니다.



    일렉트론 데스크탑 어플리케이션은 어쨌든 웹 페이지를 띄우고 해당 브라우저가 직접 인터넷으로 통신하는 구조라 일반적인 인터넷 연결 확인과는 개념이 조금 다릅니다.


    반응형