三分鐘教你用 Scarlet 寫一個(gè) WebSocket App
在移動(dòng)應(yīng)用程序中,數(shù)據(jù)層是屏幕上顯示內(nèi)容的真實(shí)來源。然而,在今年早些時(shí)候在 Tinder 中集成了 WebSocket API 時(shí),維護(hù)它成為了一個(gè)令人頭疼的問題。為了在 Android 上更輕松地集成 WebSocket,Scarlet應(yīng)運(yùn)而生。
WebSocket 是在 Android 應(yīng)用程序中實(shí)現(xiàn)數(shù)據(jù)層的選項(xiàng)之一,尤其是在應(yīng)用需要實(shí)時(shí)更新數(shù)據(jù)的情況下,例如聊天、在線多人游戲和實(shí)時(shí)提要。它在客戶端和服務(wù)器之間建立雙向連接。當(dāng)連接打開時(shí),它們可以以低開銷來回發(fā)送文本和二進(jìn)制消息。本文將教大家如何在Android應(yīng)用中快速實(shí)現(xiàn)WebSocket。
設(shè)置
要實(shí)現(xiàn) Scarlet,首先將其添加到 app/build.gradle 文件。
- dependencies {
- ...
- // scarlet
- implementation 'com.tinder.scarlet:scarlet:0.1.12'
- }
在 Scarlet 提供的示例中,RxJava 用于幫助管理 Web 套接字發(fā)送的數(shù)據(jù)流。在 app/build.gradle 中實(shí)現(xiàn)它。
- dependencies {
- // rx
- implementation 'io.reactivex.rxjava2:rxjava:2.2.21'
- implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
- implementation 'io.reactivex.rxjava2:rxkotlin:2.4.0'
- }
如果大家對 Coroutine 和 Kotlin Flow 的支持感到好奇,請參閱此處:https : //github.com/Tinder/Scarlet/issues/114
現(xiàn)在我們設(shè)置的重要部分是服務(wù)。我們可以使用websocket-echo (wss://websocket-echo.glitch.me)測試我們的 WebSocket;
創(chuàng)建接口函數(shù)
接下來,創(chuàng)建一個(gè)interface以定義與 WebSocket 通信的函數(shù)。
- interface EchoService {
- @Receive
- fun observeConnection(): Flowable<WebSocket.Event>
- @Send
- fun sendMessage(param: String)
- }
如上所示,服務(wù)接口看起來與改造非常相似。大家可以使用@Receive注解來觀察來自 WebSocket 的數(shù)據(jù)流,并用于@Send向WebSocket發(fā)送或訂閱數(shù)據(jù)。
設(shè)置好服務(wù)后,我們可以繼續(xù)在我們的活動(dòng)中實(shí)現(xiàn)服務(wù);在這種情況下,我沒有使用任何架構(gòu),只是在Activity中實(shí)現(xiàn)了服務(wù)。
- class MainActivity : AppCompatActivity() {
- ...
- private fun setupWebSocketService() {
- webSocketService = provideWebSocketService(
- scarlet = provideScarlet(
- client = provideOkhttp(),
- lifecycle = provideLifeCycle(),
- streamAdapterFactory = provideStreamAdapterFactory(),
- )
- )
- }
- private fun provideWebSocketService(scarlet: Scarlet) = scarlet.create(EchoService::class.java)
- private fun provideScarlet(
- client: OkHttpClient,
- lifecycle: Lifecycle,
- streamAdapterFactory: StreamAdapter.Factory,
- ) =
- Scarlet.Builder()
- .webSocketFactory(client.newWebSocketFactory(ECHO_URL))
- .lifecycle(lifecycle)
- .addStreamAdapterFactory(streamAdapterFactory)
- .build()
- private fun provideOkhttp() =
- OkHttpClient.Builder()
- .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
- .build()
- private fun provideLifeCycle() = AndroidLifecycle.ofApplicationForeground(application)
- private fun provideStreamAdapterFactory() = RxJava2StreamAdapterFactory()
- ...
- }
測試
現(xiàn)在我們可以通過向 WebSocket 發(fā)送一些東西來測試下代碼。WebSocket 將在它們檢索時(shí)發(fā)送相同的消息。
- class MainActivity : AppCompatActivity() {
- ...
- private fun sendMessage(message: String) {
- webSocketService.sendMessage(message)
- adapter.addItem(Message(message = message, isFromSender = true))
- }
- @SuppressLint("CheckResult")
- private fun observeConnection() {
- webSocketService.observeConnection()
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({ response ->
- Log.d("observeConnection", response.toString())
- onReceiveResponseConnection(response)
- }, { error ->
- Log.e("observeConnection", error.message.orEmpty())
- Snackbar.make(binding.root, error.message.orEmpty(), Snackbar.LENGTH_SHORT).show()
- })
- }
- private fun onReceiveResponseConnection(response: WebSocket.Event) {
- when (response) {
- is OnConnectionOpened<*> -> changeToolbarTitle("connection opened")
- is OnConnectionClosed -> changeToolbarTitle("connection closed")
- is OnConnectionClosing -> changeToolbarTitle("closing connection..")
- is OnConnectionFailed -> changeToolbarTitle("connection failed")
- is OnMessageReceived -> handleOnMessageReceived(response.message)
- }
- }
- private fun handleOnMessageReceived(message: MessageScarlet) {
- adapter.addItem(Message(message.toValue(), false))
- binding.etMessage.setText("")
- }
- private fun MessageScarlet.toValue(): String {
- return when (this) {
- is Text -> value
- is Bytes -> value.toString()
- }
- }
- ...
- }
總結(jié)
這就是本文討論的全部內(nèi)容。Scarlet 是一個(gè)很棒的庫,可讓大家訪問在 Android 應(yīng)用程序中實(shí)現(xiàn) WebSocket。大家可以通過以上教程輕松為自己的應(yīng)用設(shè)置 Scarlet ,特別是如果已經(jīng)熟悉 Retrofit 等工具。