依赖
implementation 'com.microsoft.signalr:signalr:3.1.4' // 核心库
implementation 'org.slf4j:slf4j-jdk14:1.7.25' // 日志
例子
package com.qiyougou.singnalrdemo
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.microsoft.signalr.*
import io.reactivex.Single
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception
class MainActivity : AppCompatActivity() {
private lateinit var hubConnection:HubConnection
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
hubConnection = HubConnectionBuilder.create("http://onlly.online:8000/api/chatHub")
.withTransport(TransportEnum.LONG_POLLING)
.withAccessTokenProvider(Single.defer {
Single.just("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6ImFkbWluIiwianRpIjoiMSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvZXhwaXJhdGlvbiI6IjYvNS8yMCA4OjIzOjEzIFBNIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQWRtaW4iLCJuYmYiOjE1OTEzNTYxOTMsImV4cCI6MTU5MTM1OTc5MywiaXNzIjoiT0EuUlNJLkJhY2tlbmQiLCJhdWQiOiJ3ciJ9.kXvFsXL4qDDRhMs2pM4oKpMc0h1rknoI-PbNPMgxefo")
}).build()
hubConnection.on("ReceiveMessage",{user:String,message:String ->
Log.d(javaClass.simpleName,"received message $user:$message")
},String::class.java,String::class.java)
btnConnect.setOnClickListener {
try{
hubConnection.start().blockingAwait()
Log.d(javaClass.simpleName,"Connect successfully")
}catch (e:Exception){
Log.d(javaClass.simpleName,"Connect failed...")
Log.d(javaClass.simpleName,e.message)
}
}
btnSend.setOnClickListener {
if(hubConnection.connectionState == HubConnectionState.CONNECTED){
hubConnection.send("ReceiveMessage","admin","Say hi!")
}else Log.d(javaClass.simpleName,"not connected")
}
}
override fun onDestroy() {
super.onDestroy()
hubConnection.stop()
}
}
网友评论