一、添加依赖和权限
在 build.gradle 构建脚本中 , 添加依赖 :
implementation 'org.java-websocket:Java-WebSocket:1.5.2'
在 AndroidManifest.xml 清单文件中 , 添加网络权限 :
<uses-permission android:name="android.permission.INTERNET" />
二、创建 WebSocketClient 客户端类
创建 org.java_websocket.client.WebSocketClient 子类 ;
package kim.hsl.websocketdemo
import android.util.Log
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.lang.Exception
import java.net.URI
open class MyWebSocketClient(serverUri: URI?) : WebSocketClient(serverUri) {
val TAG = "MyWebSocketClient"
override fun onOpen(handshakedata: ServerHandshake?) {
Log.i(TAG, "onOpen handshakedata=$handshakedata")
}
override fun onMessage(message: String?) {
Log.i(TAG, "onMessage message=$message")
}
override fun onClose(code: Int, reason: String?, remote: Boolean) {
Log.i(TAG, "onClose code=$code reason=$reason remote=$remote")
}
override fun onError(ex: Exception?) {
Log.i(TAG, "onError ex=$ex")
}
}