Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.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
Sockets 用于Java的Kotlin嵌套使用函数try with resource_Sockets_Kotlin_Kotlin Coroutines_Outputstream_Try With Resources - Fatal编程技术网

Sockets 用于Java的Kotlin嵌套使用函数try with resource

Sockets 用于Java的Kotlin嵌套使用函数try with resource,sockets,kotlin,kotlin-coroutines,outputstream,try-with-resources,Sockets,Kotlin,Kotlin Coroutines,Outputstream,Try With Resources,我的目标是在try-catch块中自动关闭Socket和OutputStream 在搜索和学习Java之后,我最终在Kotlin中使用了use{}。但是,嵌套的使用{}似乎无法避免: suspend fun print(): LoadingStatus { var status = LoadingStatus.LOADING withContext(Dispatchers.IO) { try { val printerSocket = S

我的目标是在try-catch块中自动关闭
Socket
OutputStream

在搜索和学习Java之后,我最终在Kotlin中使用了
use{}
。但是,嵌套的
使用{}
似乎无法避免:

suspend fun print(): LoadingStatus {
    var status = LoadingStatus.LOADING

    withContext(Dispatchers.IO) {
        try {
            val printerSocket = Socket("192.168.x.xxx", 9100)

            printerSocket.use { socket ->            <- first use{}
                socket.getOutputStream().use {       <- second use{}
                    it.write("xxx".toByteArray())

                    status = LoadingStatus.DONE
                }
            }
        } catch (e: IOException) {
            Log.e("print()", "Printing Failed: please check your network")
            status = LoadingStatus.ERROR
        }
    }

    return status
}
suspend fun print():加载状态{
var状态=LoadingStatus.LOADING
withContext(Dispatchers.IO){
试一试{
val printerSocket=Socket(“192.168.x.xxx”,9100)

printerSocket.use{socket->在
套接字及其
输出流
的这种特殊情况下,没有必要在
套接字
输出流
上使用
,因为
socket.getOutputStream()的契约规定:

关闭返回的OutputStream将关闭关联的套接字

()

因此,只要做到以下几点就足够了:

printerSocket.getOutputStream().use {
  ...
}

套接字
及其
输出流
的这种特殊情况下,
无需在
套接字
输出流
上使用
,因为
Socket.getOutputStream()的契约规定:

关闭返回的OutputStream将关闭关联的套接字

()

因此,只要做到以下几点就足够了:

printerSocket.getOutputStream().use {
  ...
}