title: Having problems sending a bitmap over the network using TCP
body: <p>I'm trying to set up a simple desktop monitoring program in C#. I've been searching around for almost an hour trying to find a working model, however anything I found either threw exceptions or was too darn complicated, making calls to obscure functions.</p>
  
  <p>I am able to capture the screen to a bitmap instance and I have had a crack at trying to send it, but at the moment, the programs run normally and close. The client throws an exception because the connection wasn't closed properly (lazy me!), but nothing else happens. No output file is written to, nothing.</p>
  
  <p>Here is the server's code</p>
  
  <pre><code>using System.IO;
  using System.Drawing;
  using System.Drawing.Imaging;
  using System.Net;
  using System.Net.Sockets;
  using System;
  
  class ScreenCapture
  {
      public static void Main()
      {
          try
          {
              TcpListener srv = new TcpListener(IPAddress.Any, 51530);
              srv.Start(1);
              TcpClient client = srv.AcceptTcpClient();
              NetworkStream ns = client.GetStream();
              StreamWriter send = new StreamWriter(ns);
              StreamReader read = new StreamReader(ns);
  
              Rectangle screenshot;
              Bitmap bitmap;
              screenshot = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
              bitmap = new Bitmap(screenshot.Width, screenshot.Height, PixelFormat.Format32bppArgb);
              Graphics g = Graphics.FromImage(bitmap);
              g.CopyFromScreen(screenshot.Left, screenshot.Top, 0, 0, screenshot.Size);
              g.Dispose();
              MemoryStream m = new MemoryStream();
              bitmap.Save(m, ImageFormat.Jpeg);
  
              byte[] data = m.ToArray();
              Console.WriteLine(data.ToString());
              send.Write(m);
          }
          catch (Exception ex)
          {
              Console.WriteLine(ex.ToString());
              Console.ReadKey();
          }
      }
  }
  </code></pre>
  
  <p>Here's the client's code:</p>
  
  <pre><code>using System;
  using System.IO;
  using System.Net;
  using System.Net.Sockets;
  using System.Drawing;
  using System.Drawing.Imaging;
  
  class RetrieveScreenShot
  {
      public static void Main()
      {
          try
          {
              TcpClient client = new TcpClient("127.0.0.1", 51530);
              NetworkStream ns = client.GetStream();
              Image receivedImage = Image.FromStream(ns);
              receivedImage.Save("output.bmp");
              ns.Close();
              client.Close();
          }
          catch (Exception ex)
          {
              Console.WriteLine(ex.ToString());
              Console.ReadLine();
          }
      }
  }
  </code></pre>