需要帮助测试TCP服务器

时间:2020-09-19 13:04:52

标签: c# tcp connection client stress-testing

我最近为我的一个项目构建了服务器。该服务器可以使用TCP连接。 (5个设备同时通信)。与之连接的Foreach设备随后将创建一个包含收到信息的新网格行。 我的问题是,如果在启动服务器之前已打开客户端,则服务器将无法处理传入的连接高峰和崩溃。我需要先启动它几次,然后才能启动它。

不幸的是,我无法在家里重现该错误以对其进行调试。是否有任何应用程序能够始终尝试连接到服务器,并在最终成功通过网络向其发送字符串时提供该应用程序?

1 个答案:

答案 0 :(得分:1)

最后,我为此编写了我的应用程序。该应用程序非常原始。它只是一直尝试重新连接未连接到服务器的所有时间,当连接成功后,它将向服务器发送连接字符串并读取答案。

如果有人想使用它,这里是代码:(要立即建立更多连接,只需运行该应用程序的更多实例或适当更改代码)

https:// pa ste bin(。)com / g0wcJXh7(很抱歉,但我只是无法将所有代码粘贴到代码块中-它始终只放在其中一部分)

static TcpClient client;
    static string ipAdress = "10.10.2.29";
    static int port = 11800;
    static string cnnMess;
    static string junkMess;
    static Byte[] bytes;
    static Byte[] bytes_junk;
    static void Main(string[] args)
    {
        //initializing variables
        Random r = new Random();
        cnnMess = string.Format("CNN?AA:BB:CC:DD:{0}!", r.Next(10, 99));
        bytes = Encoding.UTF8.GetBytes(cnnMess);
        junkMess = "JUNK!";
        bytes_junk = Encoding.UTF8.GetBytes(junkMess);


        while (true)
        {
            try
            {
                client.GetStream().Write(bytes_junk, 0, bytes_junk.Length); //App tries to send junk packet to the server (used to determine wether the connection still exist)
                Thread.Sleep(50); //Put the thread to sleep to minimize the trafic
            }
            catch //if the sending fails it means that the client is no longer connected --> reconnect
            {
                Connect();
            }
        }
        
        
    }
    static void Connect()
    {
        client = new TcpClient();
        try
        {
            client.Connect(ipAdress, port);
        }
        catch { }
        int count = 0;
        while (!client.Connected)
        {
            Thread.Sleep(500);
            count++;
            if(count >= 5)
            {
                try
                {
                    client.Connect(ipAdress, port);
                }
                catch { }
                count = 0;
                Console.WriteLine("Connection Failed - retrying");
            }
        }
        var writer = new StreamWriter(client.GetStream());
        var reader = new StreamReader(client.GetStream());
        client.GetStream().Write(bytes, 0, bytes.Length);


        Console.WriteLine(cnnMess);
        while (client.GetStream().DataAvailable)
        {
            Console.Write(client.GetStream().ReadByte());
        }
        Console.WriteLine();

        }