SoFunction
Updated on 2025-03-07

C# implements multi-threaded LAN chat system

If you think it is a little helpful, just give it a try.

Socke programming supports multiple clients and multi-threaded operations to avoid interface jamming.

Turn on socket

private void button1_Click(object sender, EventArgs e)
   {
     try
     {
       int port = (txt_port.Text);
       string host = txt_ip.Text;
       //Create endpoint       IPAddress ip = (host);
       IPEndPoint ipe = new IPEndPoint(ip, port);
       //Create Socket and start listening       newsock = new Socket(, , ); //Create a Socket object. If you use UDP protocol, you need to use a socket of type       (ipe);  //Bind EndPoint object       (0);  //Start monitoring       //Create a new socket for the newly created connection       acceptClientThread = new Thread(new ThreadStart(AcceptClient));
       ();
       SetText("Start listening");
     }
     catch (Exception exp)
     {
       (exp, );
     }
   }

Monitor ports and receive clients

/// <summary>
    /// Accept the client, which can accept multiple clients to connect at the same time, and register the connected clients to the client list.    /// </summary>
    public void AcceptClient()
    {
      try
      {
        while (true)
        {
          Socket client = ();
          ip = ;
          RegeistUser(, client);
          Thread clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));
          object o = client;
          (o);
        }
      }
      catch (Exception exp)
      {
        (exp, );
      }
    }

Receive client data and broadcast data

/// <summary>
    /// Receive client data and forward it to the target client.    /// </summary>
    public void ReceiveData(object o)
    {
      try
      {
        while (true)
        {
          Socket client = (Socket)o;
          string recvStr = "";
          byte[] recvBytes = new byte[1024];
          int bytes;
          bytes = (recvBytes, , 0); //Receive message from client          recvStr = Encoding.(recvBytes, 0, bytes);
          SendMessage(client, recvStr);
          SetText(recvStr);
          (recvStr);
        }
      }
      catch (Exception exp)
      {
        (exp, );
      }
    }

Determine whether the user registers or sends a message

/// <summary>
   /// Determine whether the user is registering or sending a message   /// </summary>
   /// <param name="p_strMessage"></param>
   public void SendMessage(Socket client,string p_strMessage)
   {
     if (p_strMessage.StartsWith("@"))
     {
       RegeistUser(p_strMessage, client);
     }
     else if (p_strMessage.StartsWith(">"))
     {
       
       DeleteClident(p_strMessage);
     }
     else
     {
       //SendMessageToTarget(p_strMessage);
       SendAllMessage(p_strMessage);
     }
   }

Register socket as specified username

/// <summary>
    /// Register socket as specified username    /// </summary>
    /// <param name="user"></param>
    /// <param name="ss"></param>
    public void RegeistUser(string user, Socket ss)
    {
      user = (0, 1);
      (user, ss);
      SendOneMessage(ss, "welcome" + user + "Connect!");
      RefreshClient();
    }

Remove client from client dictionary

/// <summary>
    /// Remove client from client dictionary    /// </summary>
    /// <param name="p_strMessage"></param>
    public void DeleteClident(string p_strMessage)
    {
      p_strMessage = p_strMessage.Remove(0, 1);
      (p_strMessage);
      RefreshClient();
    }

Mass message

/// <summary>
    /// Bulk message    /// </summary>
    /// <param name="p_strsend"></param>
    public void SendAllMessage(string p_strsend)
    {
      //(p_strsend);
      foreach (string item in )
      {
        byte[] bs = Encoding.(p_strsend);
        userSocketDict[item].Send(bs, , 0); 
      }
    }

Assign value to text box

public delegate void SetTextHandler(string text);
    /// <summary>
    /// Assign value to the text box    /// </summary>
    /// <param name="text"></param>
    private void SetText(string text)
    {
      if (rich_back.InvokeRequired == true)
      {
        SetTextHandler set = new SetTextHandler(SetText);//The delegate method parameters should be consistent with SetText        rich_back.Invoke(set, new object[] { text }); //The second parameter of this method is used to pass in the method, instead of the formal parameter text      }
      else
      {
        rich_back.Text += "\n" + text;
      }
 
    }

Connect to the server

private void button1_Click(object sender, EventArgs e)
    {
      try
      {
        user = txt_name.Text;
        int port = (txt_port.Text);
        string host = txt_ip.Text;
        //Create the endpoint EndPoint        IPAddress ip = (host);
        IPEndPoint ipe = new IPEndPoint(ip, port);  //Convert ip and port into IPEndPoint instance        //Create Socket and connect to the server        Socket c = new Socket(, , );  // Create Socket        cc = c;
        (ipe); //Connect to the server        clientThread = new Thread(new ThreadStart(ReceiveData));
        ();
        //Send the local username to the server so that the server can register the client        SendMessage("@" + txt_name.Text);
      }
      catch (ArgumentException ex)
      {
        ("argumentNullException:{0}", ex);
      }
      catch (SocketException exp)
      {
        ("SocketException:{0}",exp);
      }
    }

Send a message to the server

private void button3_Click(object sender, EventArgs e)
    {
      if (""==txt_target.Text)
      {
        ("Dialogue character not selected");
        return;
      }
      //Send information to the server      string sendStr = txt_name.Text + "@" + target + ":" + txt_message.Text;
      SendMessage(sendStr);
      rch_back.Text += "\n" + sendStr;
      txt_message.Text = "";
    }

Invisible

private void button2_Click(object sender, EventArgs e)
    {
      try
      {
        SendMessage(">" + txt_name.Text);
        //(true);
        //();
        //();
      }
      catch (Exception exp)
      {
        (exp, );
      }
    }

The above is the entire content of this article, I hope you like it.