Create Application TCP/IP server send data to multiclient C#

DevNotes
0
Phần mềm sử dụng Socket của Microsoft hỗ trợ. Client nên dùng là Helcules Terminal để quan sát quá trình gửi nhận dữ liệu

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TCP_2
{
    public partial class ServerForm : Form
    {
        private TcpListener server;
        private CancellationTokenSource cancellationTokenSource;
        private int port;
        private TcpClient[] connectedClients = new TcpClient[4];
        private readonly int[] messageIndex = new int[4];
        private int clientNumber;
        public ServerForm()
        {
            InitializeComponent();
            LoadParams();
        }

        private void LoadParams()
        {
            textBoxIp.Text = "127.0.0.1";
            textBoxPort.Text = "12345";
            textBoxDelayTime.Text = "500";
            textBoxClientNum.Text = "1";
            
        }

        private void StartServer()
        {

            try
            {
                clientNumber = int.Parse(textBoxClientNum.Text);
                port = int.Parse(textBoxPort.Text);
                server = new TcpListener(IPAddress.Parse(textBoxIp.Text), port);
                server.Start();
                labelSts.Text = "Connected";
            }
            catch (Exception ex)
            {
                labelSts.Text = ex.Message;
            }
        }

        private void StopServer()
        {
            try
            {
                server.Stop();
                server = null;
                listBoxClient.Items.Clear();
                labelSts.Text = "Disconnected";
            }
            catch (Exception ex)
            {
                labelSts.Text = ex.Message;
            }
        }

        private async Task AcceptClientsAsync(CancellationToken cancellationToken)
        {
            for (int i = 0; i < clientNumber; i++)
            {

                TcpClient client = await server.AcceptTcpClientAsync();
                connectedClients[i] = client;
                listBoxClient.Items.Add(connectedClients[i].Client.RemoteEndPoint.ToString());
                _ = HandleClientAsync(connectedClients[i], i, cancellationToken);

            }
        }

        private async Task HandleClientAsync(TcpClient client, int clientIndex, CancellationToken cancellationToken)
        {
            using (client)
            using (NetworkStream stream = client.GetStream())
            {

                while (!cancellationToken.IsCancellationRequested && client.Connected)
                {
                    try
                    {
                        byte[] messageBytes = Encoding.ASCII.GetBytes($"Message Index at {clientIndex + 1}: {messageIndex[clientIndex]} \n");
                        await stream.WriteAsync(messageBytes, 0, messageBytes.Length, cancellationToken);
                        await stream.FlushAsync(cancellationToken);
                        await Task.Delay(int.Parse(textBoxDelayTime.Text), cancellationToken);
                        messageIndex[clientIndex]++;
                        if (clientIndex > connectedClients.Length)
                        {
                            messageIndex[clientIndex] = 0;
                        }
                    }
                    catch (Exception ex)
                    {
                        labelSts.Text = ex.Message;
                    }
                }
            }
        }

        private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            cancellationTokenSource.Cancel();
            server?.Stop();
            foreach (TcpClient client in connectedClients)
            {
                client?.Close();
            }
        }

        private void buttonStartSend_Click(object sender, EventArgs e)
        {
            if (buttonStartSend.Text == "Start Send")
            {
                StartServer();
                cancellationTokenSource = new CancellationTokenSource();
                _ = AcceptClientsAsync(cancellationTokenSource.Token);
                buttonStartSend.Text = "Stop Send";
            }
            else
            {

                buttonStartSend.Text = "Start Send";
                cancellationTokenSource.Cancel();
                StopServer();
            }

        }


    }
}

Post a Comment

0 Comments
Post a Comment (0)
To Top