c# – Connecting multiple device/client with server and communicating with these connected devices?

Actually I have a written a code to established a multiple client/device connection with server. My code established a multiple a connection with server and shows me a list of connected clients after When I select a connected device and try to send messages to client it’s working fine but When I try to receive a messages from client it’s not working.

Here is my Code:

Below code established a multiple client/devices connection with server

private void btnstart_Click(object sender, EventArgs e)
          {
    
    
                  string Systemip = getlocalip();
                  txtinfo.Text = "Server IP:" + Systemip + Environment.NewLine;
                  var portno = Int32.Parse("8010");
    
                  String a = "";
    
                  IPAddress ip = IPAddress.Parse(Systemip);
                  server = new TcpListener(ip, portno);
                  server.Start();
    
                 //here environment.newline means, display msg to next line.
                  txtinfo.AppendText("Server started waiting for client.............." + Environment.NewLine);
              counter = 0;
              f = new Form1();
              Thread newone = new Thread(loop);
              newone.Start();
    
    
          }
          public delegate void messageone();
          public void mess()
          {
    
              richtxtbddata.AppendText(counter + "clien connected" + Environment.NewLine);
              richtxtbddata.AppendText("The client is from IP address: " + ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString() + Environment.NewLine);
          //    iplist.Items.Add(((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString());
              listBox1.Items.Add(counter);         //add this (((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString()); on the place of counter
          }
    
          public void loop(object obj)
          {
              connectobj = new List<Multipleconnect>();
    
              while (true)
              {
                  counter++;
    
                  socketforclient = server.AcceptSocket();
                 // ns = new NetworkStream(socketforclient);
                  connectobj.Add(new Multipleconnect
                  {
                      objectno = counter,
                      Skt = socketforclient,
                      nstream = new NetworkStream(socketforclient),
                      ip = ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString()
                  });
    
                  //Box.AppendText(counter + "Client connected");
                  richtxtbddata.Invoke(new messageone(mess));
                  Thread UserThread = new Thread(new ThreadStart(() => f.User(socketforclient)));
                  UserThread.Start();
    
              }
          }
          public void User(Socket client)
          {
              while (true)
              {
                  try
                  {
                      byte() msg = new byte(1024);
                      int size = client.Receive(msg);
                      client.Send(msg, 0, size, SocketFlags.None);
                  }
                  catch (Exception ex)
                  {
                      txtinfo.Text = "Divice Disconnected";
                  }
    
              }
    
          }

Below code is for sending and receiving a messages but In this code messages sent client/device successfully but this code is not receive a messages from client/devices.

private void btnsend_Click(object sender, EventArgs e)
       {

       isNew = true;

           if (servermsg.Text != "") {

               ns = new NetworkStream(socketforclient);
               StreamWriter writer = new StreamWriter(ns);

               writer.WriteLine(servermsg.Text + Environment.NewLine);
               txtinfo.AppendText("Server:" + servermsg.Text + Environment.NewLine);
               writer.Flush();
               writer.Close();
           }


           ns = new NetworkStream(socketforclient);
           StreamReader sr = new StreamReader(ns);
           string myCompleteMessage = string.Empty;

           if (ns.DataAvailable)
           {
               myReadBuffer = new byte(2048);
               datafinal = new double(1);

               myCompleteMessage = Encoding.ASCII.GetString(myReadBuffer, 0, readbytes);

           }

           //runn();



           if (myCompleteMessage != "")
           {
              txtinfo.AppendText("Client:" + myCompleteMessage + Environment.NewLine + Environment.NewLine);
           }

       }

If You want a complete code, It is given below:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

/// <summary>
/// single connection in working condition with old code.....
/// </summary>

namespace TCPSERVER
{
  
    public partial class Form1 : Form
    {
        List<Multipleconnect> connectobj;

        Form1 f;
        int counter = 0;
        NetworkStream ns;
        int i = 0;
        Socket socketforclient;
        TcpListener server;
        byte() myReadBuffer;
        int readbytes;
        int p = 0;
        int y;
        double() datafinal;
        double() yy;
        List<double> xx;
        string stop = "";
        Multipleconnect mulcon = new Multipleconnect();

        public Form1()
        {
            InitializeComponent();
            //txtserverip.Text = getlocalip();
         
            Featuresduringrun();
         //   Connnection();
        }

        private void btnstart_Click(object sender, EventArgs e)
        {
          
            
                string Systemip = getlocalip();
                txtinfo.Text = "Server IP:" + Systemip + Environment.NewLine;
                var portno = Int32.Parse("8010");
             
                String a = "";

                IPAddress ip = IPAddress.Parse(Systemip);
                server = new TcpListener(ip, portno);
                server.Start();

               //here environment.newline means, display msg to next line.
                txtinfo.AppendText("Server started waiting for client.............." + Environment.NewLine);
            counter = 0;
            f = new Form1();
            Thread newone = new Thread(loop);
            newone.Start();

 
        }
        public delegate void messageone();
        public void mess()
        {

            richtxtbddata.AppendText(counter + "clien connected" + Environment.NewLine);
            richtxtbddata.AppendText("The client is from IP address: " + ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString() + Environment.NewLine);
        //    iplist.Items.Add(((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString());
            listBox1.Items.Add(counter);         //add this (((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString()); on the place of counter
        }

        public void loop(object obj)
        {
            connectobj = new List<Multipleconnect>();

            while (true)
            {
                counter++;

                socketforclient = server.AcceptSocket();
               // ns = new NetworkStream(socketforclient);
                connectobj.Add(new Multipleconnect
                {
                    objectno = counter,
                    Skt = socketforclient,
                    nstream = new NetworkStream(socketforclient),
                    ip = ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString()
                });

                //Box.AppendText(counter + "Client connected");
                richtxtbddata.Invoke(new messageone(mess));
                Thread UserThread = new Thread(new ThreadStart(() => f.User(socketforclient)));
                UserThread.Start();

            }
        }
        public void User(Socket client)
        {
            while (true)
            {
                try
                {
                    byte() msg = new byte(1024);
                    int size = client.Receive(msg);
                    client.Send(msg, 0, size, SocketFlags.None);
                }
                catch (Exception ex)
                {
                    txtinfo.Text = "Divice Disconnected";
                }

            }




        }




        public static string getlocalip()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach(var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            return "not found any ip";
        }
 
        private void btnsend_Click(object sender, EventArgs e)
        {
            string aa = listBox1.SelectedItems(0).ToString();
            if (aa == null)
            {
                MessageBox.Show("Selexct a item");

            }
     

            
            if (servermsg.Text != "") {
               
                ns = new NetworkStream(socketforclient);
                StreamWriter writer = new StreamWriter(ns);
               
                writer.WriteLine(servermsg.Text + Environment.NewLine);
                txtinfo.AppendText("Server:" + servermsg.Text + Environment.NewLine);
                writer.Flush();
                writer.Close();
            }
      

            ns = new NetworkStream(socketforclient);
            StreamReader sr = new StreamReader(ns);
            string myCompleteMessage = string.Empty;

            if (ns.DataAvailable)
            {
            myReadBuffer = new byte(2062);
            int rreadbytes = ns.Read(myReadBuffer, 0, myReadBuffer.Length);
            string Client2 = Encoding.ASCII.GetString(myReadBuffer, 0, rreadbytes);
            myCompleteMessage = Client2;

            }

          
            if (myCompleteMessage != "")
            {
               txtinfo.AppendText("Client:" + myCompleteMessage + Environment.NewLine + Environment.NewLine);
            }

        }










   
  

      
  
  

 
         
   
      
        private Form activeform = null;

     
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string aa = listBox1.SelectedItems(0).ToString();
            if (aa == null)
            {
                MessageBox.Show("Selexct a item");

            }
            ////  int endindex = aa.Length - 1;
            //// int b = aa.IndexOf("}");
            ////aa = aa.Substring(15, 13);

            foreach (var ob in connectobj)
            {
                if (ob.objectno.ToString() == aa)     //write ob.ip on the place of ob.objectno
                {
                    socketforclient = ob.Skt;
                    MessageBox.Show("yes");
                }
            }
        }

  
    }
}

Below code comes another class which is used to store the multiple client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TCPSERVER
{
    class Multipleconnect
    {
        public int objectno;
        public Socket Skt;
        public string ip;
        public NetworkStream nstream;
    }
}