自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

三分鐘教你用 Scarlet 寫一個(gè) WebSocket App

移動(dòng)開發(fā) Android
在移動(dòng)應(yīng)用程序中,數(shù)據(jù)層是屏幕上顯示內(nèi)容的真實(shí)來源。然而,在今年早些時(shí)候在 Tinder 中集成了 WebSocket API 時(shí),維護(hù)它成為了一個(gè)令人頭疼的問題。

在移動(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 文件。

  1. dependencies { 
  2.     ... 
  3.     // scarlet 
  4.     implementation 'com.tinder.scarlet:scarlet:0.1.12' 

在 Scarlet 提供的示例中,RxJava 用于幫助管理 Web 套接字發(fā)送的數(shù)據(jù)流。在 app/build.gradle 中實(shí)現(xiàn)它。

  1. dependencies { 
  2.      // rx 
  3.      implementation 'io.reactivex.rxjava2:rxjava:2.2.21' 
  4.      implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' 
  5.      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ù)。

  1. interface EchoService { 
  2.  
  3.     @Receive 
  4.     fun observeConnection(): Flowable<WebSocket.Event> 
  5.  
  6.     @Send 
  7.     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ù)。

  1. class MainActivity : AppCompatActivity() { 
  2.     ... 
  3.     private fun setupWebSocketService() { 
  4.         webSocketService = provideWebSocketService( 
  5.             scarlet = provideScarlet( 
  6.                 client = provideOkhttp(), 
  7.                 lifecycle = provideLifeCycle(), 
  8.                 streamAdapterFactory = provideStreamAdapterFactory(), 
  9.             ) 
  10.         ) 
  11.     } 
  12.      
  13.     private fun provideWebSocketService(scarlet: Scarlet) = scarlet.create(EchoService::class.java) 
  14.      
  15.     private fun provideScarlet( 
  16.         client: OkHttpClient, 
  17.         lifecycle: Lifecycle, 
  18.         streamAdapterFactory: StreamAdapter.Factory, 
  19.     ) = 
  20.         Scarlet.Builder() 
  21.             .webSocketFactory(client.newWebSocketFactory(ECHO_URL)) 
  22.             .lifecycle(lifecycle) 
  23.             .addStreamAdapterFactory(streamAdapterFactory) 
  24.             .build() 
  25.              
  26.     private fun provideOkhttp() = 
  27.         OkHttpClient.Builder() 
  28.             .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)) 
  29.             .build() 
  30.              
  31.     private fun provideLifeCycle() = AndroidLifecycle.ofApplicationForeground(application) 
  32.      
  33.     private fun provideStreamAdapterFactory() = RxJava2StreamAdapterFactory() 
  34.     ... 

測試

現(xiàn)在我們可以通過向 WebSocket 發(fā)送一些東西來測試下代碼。WebSocket 將在它們檢索時(shí)發(fā)送相同的消息。

  1. class MainActivity : AppCompatActivity() { 
  2.     ... 
  3.    
  4.     private fun sendMessage(message: String) { 
  5.         webSocketService.sendMessage(message) 
  6.         adapter.addItem(Message(message = message, isFromSender = true)) 
  7.     } 
  8.      
  9.     @SuppressLint("CheckResult"
  10.     private fun observeConnection() { 
  11.         webSocketService.observeConnection() 
  12.             .observeOn(AndroidSchedulers.mainThread()) 
  13.             .subscribe({ response -> 
  14.                 Log.d("observeConnection", response.toString()) 
  15.                 onReceiveResponseConnection(response) 
  16.             }, { error -> 
  17.                 Log.e("observeConnection", error.message.orEmpty()) 
  18.                 Snackbar.make(binding.root, error.message.orEmpty(), Snackbar.LENGTH_SHORT).show() 
  19.             }) 
  20.     } 
  21.  
  22.     private fun onReceiveResponseConnection(response: WebSocket.Event) { 
  23.         when (response) { 
  24.             is OnConnectionOpened<*> -> changeToolbarTitle("connection opened"
  25.             is OnConnectionClosed -> changeToolbarTitle("connection closed"
  26.             is OnConnectionClosing -> changeToolbarTitle("closing connection.."
  27.             is OnConnectionFailed -> changeToolbarTitle("connection failed"
  28.             is OnMessageReceived -> handleOnMessageReceived(response.message) 
  29.         } 
  30.     } 
  31.  
  32.     private fun handleOnMessageReceived(message: MessageScarlet) { 
  33.         adapter.addItem(Message(message.toValue(), false)) 
  34.         binding.etMessage.setText(""
  35.     } 
  36.  
  37.     private fun MessageScarlet.toValue(): String { 
  38.         return when (this) { 
  39.             is Text -> value 
  40.             is Bytes -> value.toString() 
  41.         } 
  42.     } 
  43.      
  44.     ... 

總結(jié)

這就是本文討論的全部內(nèi)容。Scarlet 是一個(gè)很棒的庫,可讓大家訪問在 Android 應(yīng)用程序中實(shí)現(xiàn) WebSocket。大家可以通過以上教程輕松為自己的應(yīng)用設(shè)置 Scarlet ,特別是如果已經(jīng)熟悉 Retrofit 等工具。

 

責(zé)任編輯:武曉燕 來源: 程序員巴士
相關(guān)推薦

2021-10-27 05:47:53

通信協(xié)議協(xié)議網(wǎng)絡(luò)技術(shù)

2024-09-02 00:03:00

tabs組件CSS

2025-03-26 01:35:00

tabs開發(fā)組件

2024-05-16 11:13:16

Helm工具release

2009-11-09 12:55:43

WCF事務(wù)

2024-12-18 10:24:59

代理技術(shù)JDK動(dòng)態(tài)代理

2022-06-28 12:35:21

DockerPython

2022-02-17 09:24:11

TypeScript編程語言javaScrip

2021-04-20 13:59:37

云計(jì)算

2023-12-27 08:15:47

Java虛擬線程

2024-01-16 07:46:14

FutureTask接口用法

2024-08-30 08:50:00

2024-04-29 08:50:26

Python模塊BERT

2013-06-28 14:30:26

棱鏡計(jì)劃棱鏡棱鏡監(jiān)控項(xiàng)目

2020-06-30 10:45:28

Web開發(fā)工具

2022-02-21 18:16:38

Go語言枚舉

2021-12-17 07:47:37

IT風(fēng)險(xiǎn)框架

2024-07-29 12:21:12

2024-10-15 09:18:30

2021-02-03 14:31:53

人工智能人臉識別
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號