为什么这个 Kotlin Socket 连接需要这么长时间?为什么我可以做优化?

问题描述 投票:0回答:1

我是 Socket 编程和 Kotlin 的新手。上面的代码确实有响应,但大约需要 8-10 分钟,但 Python 中的相同代码大约需要 5 秒。我哪里错了,我可以做些什么来改进?

我不认为服务器端有任何问题。

package com.example.myapplication

import java.io.BufferedReader import java.io.InputStreamReader import java.io.PrintWriter import java.net.Socket import java.text.SimpleDateFormat import java.util.Date import kotlinx.coroutines.*

fun main() { 
    val server = "commdev.grizzy.com" // Custom Server address 
    val port = 3000 // Server port 
    val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") 
    val soEvent = "[SO|${dateFormat.format(Date())}]"
    runBlocking {
        launch {
            Socket(server, port).use { socket ->
                println("Connected to the server at $server on port $port")
    
                PrintWriter(socket.getOutputStream(), true).use { out ->
                    BufferedReader(InputStreamReader(socket.getInputStream())).use { `in` ->
                        // Send the SO event to the server
                        out.println(soEvent)
                        println("Sent SO event: $soEvent")
    
                        val responseSO = `in`.readLine()
                        println("Received response to SO event: $responseSO")
                    }
                }
            }
        }
    }
}
kotlin sockets client kotlin-coroutines
1个回答
0
投票

是连接时延迟还是发送消息时延迟?从

Sent SO event...
打印出来时你就必须知道这一点。

如果连接时有延迟

机器上运行的 Kotlin 代码与 Python 代码不同吗?如果是这样,可能是由于 kotlin 机器的 IP 地址所致。也许服务器正在尝试对 IP 进行反向查找(例如获取其名称),而正是 that 导致了延迟。无论如何,我会在 Kotlin 机器上使用

telnet commdev.grizzy.com 3000
并查看 telnet 连接需要多长时间。

如果延迟是在发送消息时

如果服务器没有及时响应您发送的“SO”消息,请考虑服务器如何知道您已完成发送“SO...”消息。您正在使用

out.println(..)
发送换行 (
LF
) 字符。服务器可能正在等待
CR
LF
? (CR LF、LF 和 CR 换行类型的区别

© www.soinside.com 2019 - 2024. All rights reserved.