투케이2K

463. (kotlin/코틀린) [유틸 파일] observablePingCheck : Runtime.getRuntime ping 핑 체크 수행 본문

Kotlin

463. (kotlin/코틀린) [유틸 파일] observablePingCheck : Runtime.getRuntime ping 핑 체크 수행

투케이2K 2024. 3. 14. 19:24
반응형

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Kotlin

 

[소스 코드]

        // -----------------------------------------------------------------------------------------
        // TODO [SEARCH FAST] : [Observable] : observablePingCheck : ping 체크 결과 확인
        // -----------------------------------------------------------------------------------------
        // TODO [호출 방법 소스 코드]
        // -----------------------------------------------------------------------------------------
        /*
        try {

            C_App.observablePingCheck(A_Intro@this, "google.com", 1000)
                    .subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
                    .observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
                    .subscribe(
                        { value ->

                        },
                        { error ->

                        }
                    )
                    {
                    }

        }
        catch (Exception e){
            e.printStackTrace()
        }
        */
        // -----------------------------------------------------------------------------------------
        fun observablePingCheck(mContext: Context, ip: String, pingMiliSeconds: Int): Observable<Boolean> {

            // [로직 처리 실시]
            return Observable.create { subscriber: ObservableEmitter<Boolean> ->
                try {
                    // ===============================================================
                    S_Log._D_("Ping 체크 수행 실시", arrayOf(
                        "ip :: $ip",
                        "pingMiliSeconds :: $pingMiliSeconds"
                    ))
                    // ===============================================================

                    // [사전 조건 체크 수행]
                    if (C_Util.stringNotNull(ip) === true && ip.contains(".") == true && pingMiliSeconds > 0) {

                        Handler(Looper.getMainLooper()).postDelayed({

                            if (mContext != null) {

                                val thread =
                                    Thread {
                                        try {

                                            // [IP 주소 만들기]
                                            val runTime = Runtime.getRuntime()


                                            // -----------------------------------------------------------
                                            // TODO [디바이스 연결 상태는 빠르게 응답 받을 수 있으나, 모바일 응답은 대기 시간이 있어 타임 아웃 시간 늘려야 한다]
                                            // [ip 는 test 하고 싶은 주소 삽입]
                                            // [c = 패킷을 날릴 횟수]
                                            // [W = 상대방이 응답을 주기까지 대기 시간 (Seconds)]
                                            // [s = 전송 패킷 바이트 수]
                                            // -----------------------------------------------------------
                                            //String cmd = "ping -c 1 -W 1 "+ pingIp;
                                            //String cmd = "ping -s 10 -c 1 -W 1 "+ pingIp;
                                            val cmd = "ping -s 5 -c 1 $ip"
                                            var proc: Process? = null
                                            proc = runTime.exec(cmd)
                                            //proc.waitFor()

                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                if (!proc.waitFor(pingMiliSeconds.toLong(), TimeUnit.MILLISECONDS)) {
                                                    proc.destroy()
                                                }
                                            }


                                            // --------------------------------------------------------
                                            // [여기서 반환되는 ping 테스트의 결과 값은 0, 1, 2 중 하나]
                                            // --------------------------------------------------------
                                            // [0 : 성공, 1 : fail, 2 : error]
                                            // --------------------------------------------------------
                                            val result = proc.exitValue()
                                            when (result) {
                                                0 -> S_Log.w("Ping Test", "Ping Success : $ip")
                                                1 -> S_Log.e("Ping Test", "Ping Fail : $ip")
                                                else -> S_Log.e("Ping Test", "Ping Error : $ip")
                                            }
                                            if (result == 0) {
                                                subscriber.onNext(true)
                                                subscriber.onComplete()
                                            } else {
                                                subscriber.onNext(false)
                                                subscriber.onComplete()
                                            }
                                        } catch (e: Exception) {
                                            S_Log.e("[ERROR] Ping (핑) 테스트", "Exception :: " + e.message)
                                            subscriber.onNext(false)
                                            subscriber.onComplete()
                                        }
                                    }
                                thread.start() // [스레드 수행]
                            }
                        }, 0)
                    } else {

                        // [리턴 반환]
                        S_Log._E_("Ping 체크 수행 에러", arrayOf("ERROR :: Input Data Is Null"))
                        subscriber.onNext(false)
                        subscriber.onComplete()
                    }

                } catch (e: Exception) {
                    e.printStackTrace()

                    // ------------------------------------------------------
                    // TODO [리턴 데이터 반환]
                    // ------------------------------------------------------
                    try {
                        subscriber.onNext(false)
                        subscriber.onComplete()
                    } catch (ex: Exception) {
                        ex.printStackTrace()
                    }
                }
            }
        }

[결과 출력]

 

W/Ping Test: Ping Success : google.com

 

반응형
Comments