SoFunction
Updated on 2025-03-07

C# Example code using Tcp/Udp protocol

Used: Multithreaded Delegate Socket Key-Value Team

I have done a little exercise with the video. If you are interested, you can check it out. It is more helpful for beginners.

connect:/video/BV1bZ4y1W74q?p=3&t=358

Let’s talk about nonsense and add code. Understanding in the comprehensive video. I hope the master will give me some advice on what’s wrong.

public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      myAddOnlieDelegate = AddOnlie;
      myAddTextDelegate = AddTexr;
    }
 
    private void AddTexr(string str)
    {
      //Add text to text      txt_centext.AppendText(str);
    }
 
    /// <summary>
    /// Delegate method    /// </summary>
    /// <param name="str"></param>
    /// <param name="bl"></param>
    private void AddOnlie(string str, bool bl)
    {
      if (bl)
      {
        //If true, add it        (str);
      }
      else
      {
        //Remotely delete        (str);
      }
    }
 
 
 
    //Instantiate Socket    Socket socket = new Socket(, , );
    //interface    Thread thread = null;
    //Key Value Team    Dictionary<string, Socket> Dic = new Dictionary<string, Socket>();
    //Trust    delegate void MyAddOnlieDelegate(string str,bool bl);
    delegate void MyAddTextDelegate(string str);
    MyAddOnlieDelegate myAddOnlieDelegate;
    MyAddTextDelegate myAddTextDelegate;
    private void button1_Click(object sender, EventArgs e)
    {
      #region The first step is to obtain IP and port for communication with each other      //Get IP      IPAddress IP = (txt_IP.());
      //Put the IP and port number in IPEndPoint      IPEndPoint IEnd = new IPEndPoint(IP,(txt_port.()));
      try
      {
        //Related to socket        (IEnd);
        ("The server is enabled successfully!");
      }
      catch (Exception ex)
      {
        //If you fail, you will return it directly        ("Server enabled failed" + );
        return;
      }
      //How many clients can socket monitor      (10);
      #endregion
      #region Part 2 enables multi-threading      //Start multithreading operation The method to be called when starting to execute this thread      thread = new Thread(ListenConnectingl);
      //This thread is a background thread       = true;
      //Start the thread      ();
      //Disable the button after connecting to the server       = false;
      #endregion
    }
 
    /// <summary>
    /// Methods of ongoing background threads    /// </summary>
    private void ListenConnectingl()
    {
      // Loop when using thread      while (true)
      {
        //Create a new Socket column: If there is a new client to connect to the server, give it a Socket        Socket socketConnect = ();
        //Give the client who connects to skt string        string skt = ();
        (skt, socketConnect);
        Invoke(myAddOnlieDelegate, skt, true);
        //Update the device list. You need to accept messages from different clients. Then open a thread.        Thread thr = new Thread(ReceiveMsg);
         = true;
        (socketConnect);
        
      }
    }
    /// <summary>
    /// The open send accepted thread passed directly from above. The parameters are not displayed in vs. What type is used. In the video, the object type can be used to display the base class of all types.    /// </summary>
    /// <param name="socketConnect"></param>
    private void ReceiveMsg(object socketConnect)
    {
      //as: Convert strong conversion to convert object to Socket      Socket so = socketConnect as Socket;
      while (true)
      {
        byte[] arr = new byte[1024 * 1024 * 2];
        //Define a variable        int Length = -1;
        //try
        //{
          //Receive returns an int type data if not, just close it.          Length = (arr);
        //}
        //catch (Exception)
        //{
 
        // // If there is no byte count, remove it        //  string str = ();
        //  (str);
        // // Quoted Delegation        // //Invoke(myAddTextDelegate, str+"down");        //  Invoke(myAddOnlieDelegate, str, false);
        //  break;
        //}
        
        //Add if condition        if (Length == 0)
        {
          //If there is no byte count, remove it          string str = ();
          (str);
          //The cited delegation          Invoke(myAddOnlieDelegate, str, false);
          break;
        }
        else
        {
          //If the accepted byte is successfully converted into string          string str = Encoding.(arr);
          Invoke(myAddTextDelegate, str+);
 
        }
      }
    }
    /// <summary>
    /// Send message Only byte streams can be sent    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button2_Click(object sender, EventArgs e)
    {
      //The text to be sent      string str=txt_gocentext.();
      byte[] bt = Encoding.(str);
      ///
      if ( == 0)
      {
        ("Please select the object to send");
      }
      else
      {
        foreach (String item in )
        {
          //Send to the specified socket          Dic[item].Send(bt);
          string Msg = "[send]" + item + " " + str+ ;
          //Write directly using a delegate          Invoke(myAddTextDelegate, Msg+ );
        }
      }
    }
 
    private void button3_Click(object sender, EventArgs e)
    {
      Form2 form2 = new Form2();
      ();
    }
  }

The above is the detailed content of the sample code of C# using the Tcp/Udp protocol. For more information about C# using the Tcp/Udp protocol, please pay attention to my other related articles!