簡體   English   中英

需要幫助測試 TCP 服務器

[英]Need help testing TCP server

我最近為我的一個項目構建了一個服務器。 服務器使用 TCP 連接。 (5 個設備同時與它通信)。 連接到它的 Foreach 設備然后創建一個新的網格行,其中包含收到的信息。 我的問題是,如果我在服務器啟動之前打開客戶端,服務器將無法處理傳入的連接高峰和崩潰。 在它最終啟動之前,我需要啟動它幾次。

不幸的是,我無法在家中重現錯誤以進行調試。 是否有任何應用程序能夠始終嘗試連接到服務器,並在最終成功時通過網絡向其發送字符串?

最后,我為此目的編寫了我的應用程序。 該應用程序非常原始。 它只是在未連接到服務器的所有時間嘗試重新連接,當它成功時,它會將連接字符串發送到服務器並讀取答案。

如果有人想使用它,這是代碼:(一次更多連接只需運行此應用程序的更多實例或適當更改代碼)

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();

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM