gpt4 book ai didi

android - 如何使用 kotlin 通过 TCP 连接发送和接收字符串

转载 作者:行者123 更新时间:2023-12-02 18:04:10 25 4
gpt4 key购买 nike

我在 Windows 上有一个 TCP 服务器,我想在服务器和我的 Android 设备之间发送和接收文本字符串。

我花了很多时间搜索使用 Kotlin 的示例,但没有找到任何有用的代码,所以我现在只能创建套接字并连接。

fun connect() {
try{
val soc = Socket("192.168.1.5", 1419)
val dout = DataOutputStream(soc.getOutputStream())
dout.writeUTF("1")

dout.flush()
dout.close()
soc.close()
}
catch (e:Exception){
e.printStackTrace()
}
}

最佳答案

您可以查看这个简单的示例。希望对您有帮助!

服务器:

fun main() {
val server = ServerSocket(9999)
println("Server running on port ${server.localPort}")
val client = server.accept()
println("Client connected : ${client.inetAddress.hostAddress}")
val scanner = Scanner(client.inputStream)
while (scanner.hasNextLine()) {
println(scanner.nextLine())
break
}
server.close()
}

客户:

fun main() {
val client = Socket("127.0.0.1", 9999)
client.outputStream.write("Hello from the client!".toByteArray())
client.close()
}

关于android - 如何使用 kotlin 通过 TCP 连接发送和接收字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56535473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com