SoFunction
Updated on 2025-03-06

Implementation of C# Socket communication (simultaneous listening to multiple clients)

Look at the code ~

 //Create socket object            //The first parameter: set the network addressing protocol, the second parameter sets the data transmission method, and the third parameter sets the communication protocol.            Socket serverSocket = new Socket(, , );
            //2. Bind IP port            string str = "127.0.0.1";
            int ports = 55555;
            IPAddress ip = (str);
            IPEndPoint ipENdpoint = new IPEndPoint(ip, ports);
 
            (ipENdpoint);
            //3. Turn on monitoring            (10);
            label5_Timer.Text = "Start listening...";
 
            //4. Start accepting client links            (new WaitCallback(), serverSocket); 
        }
        public void StartAcceptClient(object state)
        {
            var serverSocket = (Socket)state;
            ("The server starts accepting links from the client");
            while (true)
            {
                try
                {
                    Socket prosock = ();
                    //Save the IP address and socket of the remote linked client into the collection                    ((), prosock);
                    string ipPort = ();
                    MedicineDevice ns = new MedicineDevice();
                    SQLMachine j = new SQLMachine();                   
 
                    (ipPort, "Online");
                    // Link object information                    string stinfo = ();
                    (("Client{0}Linked on", stinfo));
 
                    (prosock);
                    //The server receives the client's message                    (new WaitCallback(), prosock);
                }
                catch (Exception e)
                {
                    return;
                    //throw;
                } 
            }
 public void ReceiveData(object obj)
        {
            var prosock = (Socket)obj;
            byte[] data = new byte[1024 * 1024];
            //Method returns the length of the data actually accepted            while (true)
            {
                int realen = 0;
                try
                {
                    realen = (data, 0, , );
                }
                catch (Exception e)
                {
                    //quit unexpectedly                    AppendTextLog(("equipment {0} quit unexpectedly", ()));                  
                    StopCOnnecte(prosock);
                    return;
                }
                if (realen <= 0)
                {
                    //The other party exits normally 
                    AppendTextLog(("equipment {0} Exit normally:", ()));             
                    }
                    ();
                    ();
                    (prosock);
                    return;
                }
                // Accepted data                string fromClientMsg = (data, 0, realen);
                AppendTextLog(("Received {0} The news is:{1}", (), fromClientMsg));}}
  private void StopCOnnecte(Socket prosock)
        {
            try
            {
                if ()
                {
                    ();
                    (100);
                }
            }
            catch (Exception ex)
            { 
            }
        }
 public void AppendTextLog(string txt)
        {
            if (textBox_Message.InvokeRequired)
            {
                textBox_Message.BeginInvoke(new Action<string>(s =>
                {
                    this.textBox_Message.Text = ("{0}\r\n{1}", s, textBox_Message.Text);
                }
                    ), txt);
                //Synchronous method                //textBox_Message.Invoke(new Action<string>(s =>
                //    {
                //        this.textBox_Message.Text = ("{0}\r\n{1}", s, textBox_Message.Text);
                //    }
                //    ), txt);
            }
            else
            {
                this.textBox_Message.Text = ("{0}\r\n{1}", txt, textBox_Message.Text);
            }
        }
//There may be missed when pasting the code'{'or'}'

Supplement: Listen listening method of C# Socket

Look at the code ~

 _serverSocket.Listen(10);
  public void Listen(int backlog);

The integer parameter of the Listen method represents the maximum number of connections queued to wait for connections. Note that this number does not include the number of connections.

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.