none
How can I make this to Multi-Client Server Remote Desktop Viewer RRS feed

  • Question

  • Hi. I am a student and new with c# programming and I wanted to create a multi-client that has a remote desktop viewer functionality.

    I have a code here but only accepts one client.

    Server.cs

    private TcpClient client;
    private TcpListener server;
    private NetworkStream mainStream;
    
    private readonly Thread Listening;
    private readonly Thread GetImage;
    
    public frmRemoteView()
    {
         try
         {
              this.client = new TcpClient();
              this.Listening = new Thread(StartListening);
              this.GetImage = new Thread(ReceiveImage);
              InitializeComponent();
         }
         catch (Exception ex)
         {
              MessageBox.Show("Error 1: " + ex.Message);
         }
    }
    
    private void StartListening()
    {
         try
         {
              while (!this.client.Connected)
              {
                   this.server.Start();
                   this.client = server.AcceptTcpClient();
              }
              this.GetImage.Start();
         }
         catch (Exception ex)
         {
              MessageBox.Show("Error 2: " + ex.Message);
         }
    }
    
    private void StopListening()
    {
         this.server.Stop();
         this.client = null;
         if (this.Listening.IsAlive) this.Listening.Abort();
         if (this.GetImage.IsAlive) this.GetImage.Abort();
    }
    
    private void ReceiveImage()
    {
         BinaryFormatter binFormatter = new BinaryFormatter();
         while (this.client.Connected)
         {
              try
              {
                   this.mainStream = this.client.GetStream();
                   pictureBoxRemoteView.Image = 
              (Image)binFormatter.Deserialize(this.mainStream);
    
                   if (!client.Connected)
                   {
                        this.Close();
                   }
              }
              catch (Exception ex)
              {
                   MessageBox.Show("Error 3: " + ex.Message);
              }
    
         }
    }
    
    protected override void OnLoad(EventArgs e)
    {
         base.OnLoad(e);
         this.server = new TcpListener(IPAddress.Any, 8888);
         this.Listening.Start();
    }


    Client.cs

    private readonly TcpClient client = new TcpClient();
    private NetworkStream mainStream;
    
    public Form1()
    {
         InitializeComponent();
    }
    
    private static Image GrabDesktop()
    {
         Rectangle bounds = Screen.PrimaryScreen.Bounds;
         Bitmap screenshot = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
         Graphics graphic = Graphics.FromImage(screenshot);
                graphic.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
         return screenshot;
    }
    
    private void SendDesktopImage()
    {
         try
         {
              BinaryFormatter binFormatter = new BinaryFormatter();
              mainStream = client.GetStream();
              binFormatter.Serialize(mainStream, 
                      GrabDesktop());
         }
         catch (Exception ex)
         {
              timer1.Stop();
              MessageBox.Show(ex.Message);
         }
    }
    
    private void timer1_Tick(object sender, EventArgs e)
    {
         SendDesktopImage();
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
         client.Connect("127.0.0.1", 8888);
         timer1.Start();
    }

    I also used the logic behind this project to accept multiple-client but failed.

    codeproject.com/Articles/16023/Multithreaded-Chat-Server

    Please help me.

    Thank you and Best Regards!

    Tuesday, November 5, 2019 3:07 AM

All replies

  • Do you have a specific question? In fact, there is no question here whatsoever ... oh but the title says how can I. That is not much of a question, it should at least be in the main text and then at least you will be more likely to make it more complete.


    Sam Hobbs
    SimpleSamples.Info

    Tuesday, November 5, 2019 3:46 AM
  • Yes, Sam, of course Bryan has a question ... he wants to know what to do to make his Server accept more than one Client. 

    Bryan, in your Server code, try experimenting with using a List<TcpClient> to store multiple clients. That's just off the top of my head and I have it thought it through any more than that ... but I think you'd be able to make it work. Give it a try.

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Tuesday, November 5, 2019 6:05 AM
    Moderator
  • Hi BryanBalaga,

    Thank you for posting here.

    Here is a code example that allows your server to receive multiple clients.

    You can refer to this.

    Server:

    namespace ServerSocket
    {
        class Program
        {
            static readonly object _lock = new object();
            static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();
    
            static void Main(string[] args)
            {
                int count = 1;
    
                TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000);
                ServerSocket.Start();
    
                while (true)
                {
                    TcpClient client = ServerSocket.AcceptTcpClient();
                    lock (_lock) list_clients.Add(count, client);
                    Console.WriteLine("Someone connected!!");
    
                    Thread t = new Thread(handle_clients);
                    t.Start(count);
                    count++;
                }
            }
    
            public static void handle_clients(object o)
            {
                int id = (int)o;
                TcpClient client;
    
                lock (_lock) client = list_clients[id];
    
                while (true)
                {
                    NetworkStream stream = client.GetStream();
                    byte[] buffer = new byte[1024];
                    int byte_count = stream.Read(buffer, 0, buffer.Length);
    
                    if (byte_count == 0)
                    {
                        break;
                    }
    
                    string data = Encoding.ASCII.GetString(buffer, 0, byte_count);
                    broadcast(data);
                    Console.WriteLine(data);
                }
    
                lock (_lock) list_clients.Remove(id);
                client.Client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
    
            public static void broadcast(string data)
            {
                byte[] buffer = Encoding.ASCII.GetBytes(data + Environment.NewLine);
    
                lock (_lock)
                {
                    foreach (TcpClient c in list_clients.Values)
                    {
                        NetworkStream stream = c.GetStream();
    
                        stream.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }
    }
    

    Client:

    namespace SocketClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                int port = 5000;
                TcpClient client = new TcpClient();
                client.Connect(ip, port);
                Console.WriteLine("client connected!!");
                NetworkStream ns = client.GetStream();
                Thread thread = new Thread(o => ReceiveData((TcpClient)o));
    
                thread.Start(client);
    
                string s;
                while (!string.IsNullOrEmpty((s = Console.ReadLine())))
                {
                    byte[] buffer = Encoding.ASCII.GetBytes(s);
                    ns.Write(buffer, 0, buffer.Length);
                }
    
                client.Client.Shutdown(SocketShutdown.Send);
                thread.Join();
                ns.Close();
                client.Close();
                Console.WriteLine("disconnect from server!!");
                Console.ReadKey();
            }
    
            static void ReceiveData(TcpClient client)
            {
                NetworkStream ns = client.GetStream();
                byte[] receivedBytes = new byte[1024];
                int byte_count;
    
                while ((byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length)) > 0)
                {
                    Console.Write(Encoding.ASCII.GetString(receivedBytes, 0, byte_count));
                }
            }
        }
    }
    
    

    Hope my solution could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, November 5, 2019 9:49 AM