kotlin 协程 TCP 发送接收demo
时间: 2023-09-15 11:19:09 浏览: 47
以下是一个简单的 Kotlin 协程 TCP 发送接收 demo:
```kotlin
import kotlinx.coroutines.*
import java.net.InetSocketAddress
import java.net.Socket
import java.nio.ByteBuffer
import java.nio.channels.AsynchronousChannelGroup
import java.nio.channels.AsynchronousSocketChannel
import java.util.concurrent.Executors
suspend fun sendAndReceive() {
val group = AsynchronousChannelGroup.withThreadPool(Executors.newSingleThreadExecutor())
val socket = AsynchronousSocketChannel.open(group)
socket.connect(InetSocketAddress("localhost", 12345)).await()
// 发送数据
val buffer = ByteBuffer.wrap("Hello, server!".toByteArray())
socket.write(buffer).await()
// 接收数据
val receiveBuffer = ByteBuffer.allocate(1024)
socket.read(receiveBuffer).await()
receiveBuffer.flip()
val receivedData = String(receiveBuffer.array(), 0, receiveBuffer.limit())
println("Received data: $receivedData")
socket.close()
group.shutdown()
}
fun main() = runBlocking {
sendAndReceive()
}
```
在上面的代码中,我们创建了一个 `AsynchronousChannelGroup`,用于管理异步通道。然后我们打开一个异步 socket 通道,并连接到服务器。接着,我们将要发送的数据封装成一个 byte buffer,并使用 `await()` 方法来等待 socket 写入操作完成。然后我们再创建一个接收数据的 byte buffer,并使用 `await()` 方法等待 socket 读取操作完成。最后,我们将接收到的数据转换成字符串并打印出来。最后,我们关闭 socket 和 channel group。
需要注意的是,在上面的代码中,我们使用了 `runBlocking` 来运行协程,这将阻塞当前线程直到所有协程都完成。如果您的应用程序中已经有一个事件循环,您也可以使用 `GlobalScope.launch` 来运行协程,从而不会阻塞当前线程。
另外,还要注意在使用协程时需要导入以下依赖:
```gradle
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-nio:x.x.x")
```
其中,`x.x.x` 表示您使用的 Kotlin 协程库的版本号。