728x90
1. AndroidManifest.xml์ ์์ฑ
<uses-permission android:name="android.permission.INTERNET" />
2. build.gradle(Module)์ ์์ฑ
dependencies {
implementation 'com.squareup.okhttp3:okhttp:3.12.12'
...
}
3. ListenerClass ์์ฑ
import android.util.Log
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
class WebSocketListener : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response?) {
webSocket.send("{\"type\":\"ticker\", \"symbols\": [\"BTC_KRW\"], \"tickTypes\": [\"30M\"]}")
webSocket.close(NORMAL_CLOSURE_STATUS, null) //์์ ๊ฒฝ์ฐ ๋์์์ด ์๋ฒ์ ํต์ ํจ
}
override fun onMessage(webSocket: WebSocket?, text: String) {
Log.d("Socket","Receiving : $text")
}
override fun onMessage(webSocket: WebSocket?, bytes: ByteString) {
Log.d("Socket", "Receiving bytes : $bytes")
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
Log.d("Socket","Closing : $code / $reason")
webSocket.close(NORMAL_CLOSURE_STATUS, null)
webSocket.cancel()
}
override fun onFailure(webSocket: WebSocket?, t: Throwable, response: Response?) {
Log.d("Socket","Error : " + t.message)
}
companion object {
private const val NORMAL_CLOSURE_STATUS = 1000
}
}
webSocket.send()๋ฅผ ํตํด ์๋ฒ๋ก ๋ฉ์์ง๋ฅผ ๋ณด๋ธ๋ค.
override fun onMessage()๋ฅผ ํตํด ์๋ฒ๋ก๋ถํฐ ๋ฉ์์ง๋ฅผ ๋ฐ๋๋ค.
4. ์ฌ์ฉ๋ฐฉ๋ฒ
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import okhttp3.OkHttpClient
import okhttp3.Request
class MainActivity : AppCompatActivity() {
private lateinit var client: OkHttpClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
client = OkHttpClient()
val request: Request = Request.Builder()
.url("wss://pubwss.bithumb.com/pub/ws")
.build()
val listener: WebSocketListener = WebSocketListener()
client.newWebSocket(request, listener)
client.dispatcher().executorService().shutdown()
}
}
url์ ๊ฒฝ์ฐ ์๋ฒ ์ฃผ์๋ฅผ ๋ฃ์ผ๋ฉด ๋๋ค.
์ฑ์ด ์ข ๋ฃ๋์ด๋ ๋ฐฑ๊ทธ๋ผ์ด๋์์ ๊ณ์ ํต์ ํ๋ฏ๋ก ์ ์ ํ ์๋ช ์ฃผ๊ธฐ ๊ด๋ฆฌ๊ฐ ํ์ํ๋ค.
์ฐธ๊ณ ์ฌ์ดํธ
https://ssaurel.medium.com/learn-to-use-websockets-on-android-with-okhttp-ba5f00aea988
https://trinitytuts.com/connect-to-websocket-on-android-using-okhttp/
728x90