使用Scarlet收听服务器响应

时间:2019-05-21 16:30:09

标签: java android kotlin

所以我最近使用了猩红色的WebSocket成功地将数据在线发送到服务器,但是问题是我应该从服务器获得响应但什么也没得到。 下面是我的代码:

class MainActivity : AppCompatActivity() {

    @SuppressLint("CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val socketInit = ServerClass(application)
        socketInit.socket.observeWebSocketEvent()
            .filter { it is WebSocket.Event.OnConnectionOpened<*> }
            .subscribe({
                val data =  "{ \"lat\": 40.5555555555, \"lng\": 37.55564555554545, \"userId\": 2}"
                val send = LocationAction(data =data)

                socketInit.socket.subscribe(send)
                Log.d("TAG_SUB",send.toString())


        },{
            Log.e("TAG", "Error while observing socket ${it.cause}")
        })


        socketInit.socket.observeTicker().subscribe({
            idText.text  =it
            Log.d("TAG", "Observed: $it")
        },
            {
                Log.e("TAG", "Error while observing ticker ${it.cause}")
            })


    }

}

这是我的界面

interface SocketService {
    @Receive
    fun observeWebSocketEvent(): Flowable<WebSocket.Event>
    @Send
    fun subscribe(action: LocationAction)

    @Receive
    fun observeTicker(): Flowable<String>
}

该类波纹管包含我的猩红色实现和我的套接字URL

class ServerClass(application: Application): MainApplication() {

    private val lifecycle = AndroidLifecycle.ofApplicationForeground(application = application)
    private val backoffStrategy = ExponentialWithJitterBackoffStrategy(5000, 5000)

    private val okHttpClient = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .build()

    val socket = Scarlet.Builder()
        .webSocketFactory(okHttpClient.newWebSocketFactory("https://staging.kross.app/api/v1/notification/update"))
        .addMessageAdapterFactory(MoshiMessageAdapter.Factory())
        .addStreamAdapterFactory(RxJava2StreamAdapterFactory())
        .backoffStrategy(backoffStrategy)
        .lifecycle(lifecycle)
        .build()
        .create<SocketService>()


}

observeTicker函数应该是我侦听来自服务器的响应但没有任何反应的地方。请帮助我

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,直到找到一种方法来捕获来自套接字的消息。

我通过这种方式捕获消息:

        socketInit.socket.observeWebSocketEvent()               
            .subscribe {
                when (it) {
                    is WebSocketEvent.OnConnectionOpened -> {
                        //I do the Subscription Here the 1st message to the webserver 
                    }

                    is WebSocketEvent.OnConnectionClosing -> {
                        //Connection Closing
                    }

                    is WebSocketEvent.OnConnectionFailed -> {
                        //If connection fails
                    }

                    is WebSocketEvent.OnMessageReceived -> {                          
                        //I'm doing it here!! If you parse the it.message.toString()
                        //You can transform the response into a JSON Object like this
                        val x  : Response = Gson().fromJson(it.message.toString(), Response::class.java) 
                    }

希望这对您有帮助