以下是一个实现该功能的 C# 方法:

public static string SendHandshake()
{
    const int maxTries = 50;
    const int maxTriesAfterSuccess = 24;
    const int handshakeInterval = 20;
    const int tInterval = 3;

    int tries = 0;
    int tCount = 0;
    bool success = false;

    while (tries < maxTries && !success)
    {
        Console.Write('?');
        Thread.Sleep(handshakeInterval);
        if (Console.KeyAvailable)
        {
            ConsoleKeyInfo key = Console.ReadKey(true);
            if (key.KeyChar == '.')
            {
                success = true;
                Console.WriteLine('.');
            }
        }
        tries++;
    }

    if (success)
    {
        while (tCount < maxTriesAfterSuccess)
        {
            Console.Write('T');
            Thread.Sleep(tInterval);
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey(true);
                if (key.KeyChar == 'T')
                {
                    tCount++;
                }
            }
        }

        if (tCount >= maxTriesAfterSuccess)
        {
            return '.';
        }
    }

    return "";
}

该方法使用了一些常量来控制握手和 T 的发送间隔以及最大尝试次数。在握手阶段,每次发送 ? 后等待 20 毫秒,如果在等待期间有字符输入,就判断该字符是否为 ., 如果是,则表示握手成功,输出 . 并标记 success 为 true。如果连续尝试 50 次都没有握手成功,就退出握手阶段。

在握手成功后,该方法进入 T 发送阶段,每次发送 T 后等待 3 毫秒。如果在等待期间有字符输入,就判断该字符是否为 T,如果是,则增加 tCount 的计数器。如果 tCount 达到了 24,就表示成功接收到了至少 24 个 T,返回 .。如果 T 发送阶段连续尝试 24 次都没有成功接收到 24 个 T,就退出 T 发送阶段,返回空字符串。

C# 握手协议:发送 '?' 接收 '.' 成功,发送 'T' 返回数据

原文地址: https://www.cveoy.top/t/topic/jGpq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录