Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/181.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在连接套接字之前缓冲消息_Android_Sockets_Kotlin_Kotlin Coroutines - Fatal编程技术网

Android 在连接套接字之前缓冲消息

Android 在连接套接字之前缓冲消息,android,sockets,kotlin,kotlin-coroutines,Android,Sockets,Kotlin,Kotlin Coroutines,因此,我正在编写一个聊天信使,应用程序中的大部分通信都是通过套接字进行的 我使用scarlet作为我的套接字库(对于我的问题来说并不重要,只是想让您知道),我使用协程/通道/流来生成反应流 现在,有时套接字可能会断开并重新连接(或在第一次连接时),然后我必须通过套接字发送一些“同步”消息。我现在有一个名为“send”的方法,它为套接字接收消息并通过套接字发送。问题是,如果套接字尚未连接,消息就会丢失。这是因为当您通过断开连接的套接字发送消息时,它会丢失 我的问题是:在套接字未连接的情况下,缓冲消

因此,我正在编写一个聊天信使,应用程序中的大部分通信都是通过套接字进行的

我使用scarlet作为我的套接字库(对于我的问题来说并不重要,只是想让您知道),我使用协程/通道/流来生成反应流

现在,有时套接字可能会断开并重新连接(或在第一次连接时),然后我必须通过套接字发送一些“同步”消息。我现在有一个名为“send”的方法,它为套接字接收消息并通过套接字发送。问题是,如果套接字尚未连接,消息就会丢失。这是因为当您通过断开连接的套接字发送消息时,它会丢失

我的问题是:在套接字未连接的情况下,缓冲消息然后发送所有“缓冲”消息的最佳方式是什么

到目前为止,我的想法是:

  • 使用映射/列表将消息添加到套接字中,并在套接字联机后立即对其进行迭代并发送消息。问题是,在对消息进行迭代时,套接字可能会再次脱机,然后一些消息会再次丢失

  • 我最喜欢的想法是:创建一个kotlin
    频道
    。在send方法中,我总是将消息添加到通道中。在额外的协同程序中,我会有如下代码:

  • 通道将有足够大的缓冲区,不总是挂起调用函数
    send()
    (例如,100,但我不知道会占用多少资源)


    我对这个解决方案不是100%满意,我不知道它是否有任何缺陷,如果您能分享您对这个问题的想法和解决方案,我将非常高兴。

    这是因为当您通过断开连接的套接字发送消息时,它就会丢失。
    不可能。我不是说迷路,而是说如果没有连接就不可能发送消息。
    launch {
                while (true) {
                    subscribeState().first { it == State.Connected } // As far as I know this will block the coroutine and wait until it the first element is found, did I get this right?
                    val request = channel.receive() // It should be connected and we are waiting until the next request
                    if (getState() == State.Connected) { // Check again because we vould be offline again
                        jooyService.sendMessage(request) // Send message to socket
                    } else {
                        channel.send(request) // Put message back into channel as we could not handle it
                    }
                }
    }