kotlin 协程 TCP demo
时间: 2023-09-15 10:19:03 浏览: 79
以下是基于 Kotlin 协程的 TCP Demo。它使用 Kotlin 协程中提供的 `Socket`、`ServerSocket` 等类来完成 TCP 通信。
1. 客户端:
```kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket
fun main() = runBlocking {
val socket = Socket("localhost", 12345)
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
val writer = PrintWriter(socket.getOutputStream(), true)
GlobalScope.launch(Dispatchers.IO) {
while (true) {
val line = reader.readLine()
println("Server: $line")
}
}
while (true) {
val input = readLine() ?: break
writer.println(input)
}
}
```
2. 服务端:
```kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.ServerSocket
fun main() = runBlocking {
val serverSocket = ServerSocket(12345)
while (true) {
val socket = serverSocket.accept()
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
val writer = PrintWriter(socket.getOutputStream(), true)
GlobalScope.launch(Dispatchers.IO) {
while (true) {
val line = reader.readLine()
println("Client: $line")
writer.println("You said: $line")
}
}
}
}
```
在运行客户端和服务端之后,可以在客户端输入消息并发送到服务端,服务端会将消息回显给客户端。
阅读全文