본문 바로가기

안드로이드

안드로이드 통신 방법에 대하여

소켓 연결

소켓 연결방식에서는 클라이언트와 서버가 특정 포트를 통해 연결을 계속 유지하고 있기 때문에 실시간으로 양방향 통신을 할 수 있는데요, 주로 동영상 스트리밍이나, 온라인 게임등에서 사용되는 연결방식입니다. [1]

 

소켓은 네트워크 상의 두 프로그램 사이에서 일어나는 양방향 통신중 한 쪽의 엔드 포인트를 의미합니다. 여기서 엔드포인트란 IP와 포트의 조합을 뜻합니다.

  • 서버와 클라이언트 간에 서로 연결이 되어 계속해서 데이터를 주고 받는 통신.
  • 온라인 상태를 유지함 (ex/ 온라인 게임)
  • 일반 자바 프로그램에서 구현하는 방법과 동일
  • 사용자 접속 관리 등 많은 기능 구현해야 해서 서버 구현이 어려운 편 [2]

 

HTTP 연결

 

HTTP는 HTML 문서와 같은 리소스들을 가져올 수 있도록 해주는 프로토콜입니다. HTTP는 웹에서 이루어지는 모든 데이터 교환의 기초이며, 클라이언트-서버 프로토콜이기도 합니다. 클라이언트-서버 프로토콜이란 (보통 웹브라우저인) 수신자 측에 의해 요청이 초기화되는 프로토콜을 의미합니다. 

  • 웹서버를 사용.
  • 웹브라우저가 서버에 접속해서 데이터를 주고 받는 통신.
  • 온라인 상태를 유지하지 않음(connetionsless, stateless)
  • 용건이 있을때만 연결 했다가 용건이 없으면 연결 종료 따라서 서버가 클라이언트를 기억하기위해 쿠기나 세션을 이용

 

안드로이드 HTTP 통신 라이브러리

안드로이드에는 HTTP 통신을 구현하는 여러가지 라이브러리가 있습니다.

HttpClient → HttpUrlConnection → Volley → OkHttp → Retrofit → Ktor 순으로 변화

 

OkHttp 

OkHttp는 Android 및 Java 애플리케이션을 위한 효율적인 HTTP 및 HTTP / 2 클라이언트입니다.

연결 풀링 (HTTP / 2를 사용할 수없는 경우), 투명한 GZIP 압축 및 응답 캐싱과 같은 고급 기능이 함께 제공되어 반복되는 요청에 대해 네트워크를 완전히 피할 수 있습니다.

 

Retrofit 

retrofit은 네트워크로 부터 전달된 데이터를 프로그램에서 필요한 형태의 객체로 받을 수 있는 Httpclient 라이브러리입니다. Retrofit 에서는 Request , Response 설정 등 반복적인 작업을 라이브러리에서 넘겨서 처리하므로 작업량이 줄어들고 사용하기 굉장히 편리합니다. 그래서 Retrofit 의 장점을 요약 하지면 속도, 편의성, 가독성이라고 할 수 있습니다.

 

Ktor

Jetbrains에서 개발한 Ktor는 코틀린을 이용해 비동기 서버와 클라이언트를 구축할수 있게 해주는 라이브러리입니다. 1.6.3 버전까지 발표되어 있으며 현재도 활발한 업데이트가 이루어지고 있습니다

 

 

<실습 결과>

블로그 검색 앱

 

 

실습내용

 

카카오 API를 활용 하여 okhttp, retrofit 라이브러리와 예제코드[6] 를 활용하여 실습을 진행했습니다.

카카오 API 주소: https://developers.kakao.com/docs/latest/ko/daum-search/dev-guide#search-blog

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

 

 

 

 

 

<BlogSearchApi>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import com.example.blogsearch.data.model.SearchResponse
import com.example.blogsearch.util.Constants.API_KEY
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Query
 
interface BlogSearchApi {
 
    @Headers("Authorization: KakaoAK $API_KEY")
    @GET("v2/search/blog")
    suspend fun searchBlogs(
        @Query("query") query: String,
        @Query("sort") sort: String,
        @Query("page") page: Int,
        @Query("size") size: Int,
    ): Response<SearchResponse>
}
cs

 

 

<RetrofitInstance>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.example.blogsearch.data.api
 
import com.example.blogsearch.data.api.BlogSearchApi
import com.example.blogsearch.util.Constants.BASE_URL
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
 
object RetrofitInstance {
    private val okHttpClient: OkHttpClient by lazy {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
            .setLevel(HttpLoggingInterceptor.Level.BODY)
        OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .build()
    }
 
    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .addConverterFactory(MoshiConverterFactory.create())
            .client(okHttpClient)
            .baseUrl(BASE_URL)
            .build()
    }
 
    val api: BlogSearchApi by lazy {
        retrofit.create(BlogSearchApi::class.java)
    }
}
cs

 

<Model>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.example.blogsearch.data.model
 
 
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
 
@JsonClass(generateAdapter = true)
data class Blog(
    val title: String,
    val contents:String,
    val url:String,
    val blogname:String,
    val thumbnail:String,
    val datetime:String
)
 
cs

 

 

 

 

참고

[1] https://cliearl.github.io/posts/android/android-http-library-review/

[2] https://velog.io/@jaeyunn_15/Network-Socket

[3] https://developer.mozilla.org/ko/docs/Web/HTTP/Overview

[4] https://developers.kakao.com/docs/latest/ko/daum-search/dev-guide#search-blog

[5] https://goni95.tistory.com/79

[6] https://github.com/cliearl/book-search-app/tree/Practice02

[7] https://goni95.tistory.com/79

 

'안드로이드' 카테고리의 다른 글

[안드로이드] 디컴파일 실습  (0) 2023.06.10
Relative Layout에 대하여  (0) 2023.04.16
[Andorid] MVVM Pattern  (0) 2023.03.07
URI Scheme, AppLink, Deferred depp Link 정의  (0) 2023.02.14
안드로이드 url scheme  (0) 2023.01.31