winforms 如何使用多线程创建多个TCP客户端连接?

xqkwcwgp  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(139)

我对下面的代码有一个问题。函数的目的是创建多个TCP客户端(我在winform中的文本框中引入我想要的数字)并将它们连接到服务器,每个使用不同的线程。我还想为每个客户端分配不同的端口。我尝试使用随机函数生成随机数并将每个分配为客户端的端口,但不知何故,随机函数阻塞了主ui线程,所以我想出了一个更好的方法是使用一个变量,每次创建客户端时递增它,然后将其分配为端口。问题是我的方法都不起作用。当我运行应用程序并按下连接按钮时,它只记录“0 of x clients has connected”(x是我在文本框中引入的数字,代表我想连接多少个客户端)。

private void BtnConnect_Click(object sender, EventArgs e)
        {
            string hostname = txtIP.Text;
            int numberOfConnectedClients = 0;
            int port;
            int clientPort = 30000;



            if (!int.TryParse(txtPort.Text, out port))
            {
                MessageBox.Show("Please enter a valid port number!");
                return;
            }

            if (string.IsNullOrWhiteSpace(hostname))
            {
                MessageBox.Show("Please enter an IP address!");
                return;
            }

            try
            {
                int.TryParse(txtNumberOfDevices.Text, out totalNumberOfClients);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error : {ex.Message}. Enter a valid number of clients.");
            }
            if (totalNumberOfClients <= 0)
            {
                MessageBox.Show("Enter a valid number of clients.");
                return;
            }



            //  clients = new List<TcpClient>();
            //   clients.Add(client);

            

               for (int i = 1; i <= totalNumberOfClients; i++)
               {
                   Thread clientThread = new Thread(() =>
                   {
                       try
                       {

                            client = new TcpClient();

                           client.Connect(hostname, clientPort);

                           WriteLog($"The client {i} has connected to server on port {clientPort}");

                           Interlocked.Increment(ref numberOfConnectedClients);


                       }
                       catch (Exception ex)
                       {
                           WriteLog($"Client {i} couldn't connect on port {clientPort}. Error : {ex.Message}");
                       }

                   });

                   clientThread.Start();
                   clientPort++;

                   // Thread.Sleep(100);


               }

               WriteLog($"{numberOfConnectedClients} clients from {totalNumberOfClients} clients have connected!");

          

        }

请给予我一个解决方案,成功地连接在不同的线程和不同的端口上的客户端。

fkaflof6

fkaflof61#

也许这可以帮助!检查它...添加你需要的到你的类!

static void Main(string[] args)
    {
        Program program = new Program();
        program.StartUp();

    }
    /// <summary>
    /// Main coordinator
    /// </summary>
    void StartUp()
    {           
        Task T1 = StartSockets();
        Task.WaitAll(T1);
    }`
    ///<summary>
    /// Async void task to connect to different sockets
    /// </summary>
    /// <returns></returns>
    public async Task StartSockets()
    {
        try
        {
            for (int i = 1; i <= 3; i++)
            {
                await Task.Run(() => Socket_Method("192.168.0."+i+"", 8080));
            }
        }
        catch (Exception f)
        {
            //LOGGEN.Log(@"-------------------- JsonConvert.SerializeObject(f));
            Thread.Sleep(800);
        }
    }

    /// <summary>
    /// This sockets connects to a passive TCP/IP server a sends a JSON.
    /// </summary>
    /// <param name="IP">IP From passive TCP/IP Server</param>
    /// <param name="Port">Connection port from passive TCP/IP server</param>
    void Socket_Method(string IP, Int32 Port)
    {
        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            using (socket)
            {
                socket.Connect(new IPEndPoint(IPAddress.Parse(IP), Port));
                while (true)
                {
                    Thread.Sleep(1000);
                    socket.Send(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(BoltRadar_Json)));
                    //LOGGEN.Log(@"\-----------JsonConvert.SerializeObject(BoltRadar_Json));
                    socket.Send(Encoding.ASCII.GetBytes("\r"));
                }
            }
        }
        catch (Exception f)
        {
            socket.Close();
            //LOGGEN.Log(@"--------------JsonConvert.SerializeObject(f).ToString());
            StartUp();
        }

    }

相关问题