前言
本篇文章讲述的是WebSocket在Android中的应用,为还不会使用WebSocket的小伙伴提供一点思路,希望能帮助到大家!!!
一、WebSocket是什么?
测试网站:https://www.websocket.org/echo.html
二、使用步骤
1.引入库
implementation "org.java-websocket:Java-WebSocket:1.4.0"
2.创建JavaWebClientService用来连接服务器
01.覆写父类的方法
class JWebSocketClientService : Service() {
var client: JWebsocketClient?= null
private val mBinder = InnerIBinder()
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
initSocketClient()
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE)
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(intent: Intent?): IBinder = mBinder
override fun onDestroy() {
closeConnect()
super.onDestroy()
}
...
02.初始化WebSocketClient,定义连接、发送消息、断开连接的方法
private fun initSocketClient() {
val uri = URI.create("ws://echo.websocket.org")
client = object : JWebsocketClient(uri) {
override fun onMessage(message: String?) {
Log.d("hy55", "收到的消息:$message")
val intent = Intent()
intent.action = "CCTV5"
intent.putExtra("message", message)
sendBroadcast(intent)
}
}
connect()
}
fun sendMsg(msg: String) {
client!!.send(msg)
}
private fun connect() {
object : Thread() {
override fun run() {
try {
client?.connectBlocking()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}.start()
}
fun closeConnect() {
try {
client?.close()
} catch (e: Exception) {
e.printStackTrace()
} finally {
client = null
}
}
03.定义心跳检测的方法
private val HEART_BEAT_RATE: Long = 10 * 1000
private val mHandler = Handler()
private val heartBeatRunnable = object : Runnable {
override fun run() {
Log.i("JWebSocketClientService", "心跳包检测websocket连接状态")
if (client != null) {
if (client!!.isClosed) {
reconnectWs()
}
} else {
initSocketClient()
}
mHandler.postDelayed(this, HEART_BEAT_RATE)
}
}
private fun reconnectWs() {
mHandler.removeCallbacks(heartBeatRunnable)
object : Thread() {
override fun run() {
try {
Log.e("JWebSocketClientService", "开启重连")
client!!.reconnectBlocking()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}.start()
}
inner class InnerIBinder : Binder() {
fun getService(): JWebSocketClientService = this@JWebSocketClientService
}
3.创建JavaWebClient
abstract class JWebsocketClient(serverUri: URI) : WebSocketClient(serverUri) {
override fun onOpen(handshakedata: ServerHandshake?) {
Log.i("JWebSocketClient", "onOpen()")
}
override fun onMessage(message: String?) {
Log.i("JWebSocketClient", "onMessage()")
}
override fun onClose(code: Int, reason: String?, remote: Boolean) {
Log.i("JWebSocketClient", "onClose()")
}
override fun onError(ex: Exception?) {
Log.i("JWebSocketClient", "onError()")
}
}
4.使用WebSocketClientService和WebsocketClient
01.启动Service、绑定Service、注册广播
class MainActivity : AppCompatActivity() {
private lateinit var tv_message: TextView
private var client: JWebsocketClient? = null
private val serviceConnection = InnerServiceConnection()
private var binder: JWebSocketClientService.InnerIBinder? = null
private var jWebSClientService: JWebSocketClientService? = null
private var chatMessageReceiver: ChatMessageReceiver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val et_message = findViewById<EditText>(R.id.et_message)
val btn_send = findViewById<Button>(R.id.btn_send)
tv_message = findViewById(R.id.tv_message)
startJWebSClientService()
bindService()
doRegisterReceiver()
btn_send.setOnClickListener{
if (client != null && client!!.isOpen) {
Log.d("hy55", "${et_message.text}")
jWebSClientService!!.sendMsg(et_message?.text.toString())
}
}
}
02.启动Service、绑定Service、注册广播的具体实现
private fun startJWebSClientService() {
val intent = Intent(this, JWebSocketClientService::class.java)
startService(intent)
}
private fun bindService() {
val bindIntent = Intent(this, JWebSocketClientService::class.java)
bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE)
}
inner class InnerServiceConnection : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.d("Service", "onServiceConnected()->当Activity和Service连接")
binder = service as JWebSocketClientService.InnerIBinder
jWebSClientService = binder!!.getService()
client = jWebSClientService!!.client
}
override fun onServiceDisconnected(name: ComponentName) {
Log.d("Service", "onServiceConnected()->当Activity和Service断开连接")
}
}
03.定义广播类以及注册广播类
inner class ChatMessageReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val message = intent.getStringExtra("message")
tv_message.append(message)
}
}
private fun doRegisterReceiver() {
chatMessageReceiver = ChatMessageReceiver()
val filter = IntentFilter("CCTV5")
registerReceiver(chatMessageReceiver, filter)
}
总结
这篇文章是对WebSocket简单使用的介绍,但万变不离其宗,所有复杂的应用都是基于最简单的原理!!!
|