I'm making a Remote Desktop application using TCP, I've tried/searched for many ways to capture the screen and send it but they all do the same thing.
To Send:
- Capture the screen using Bitmap and the copyfrom method
- Use memorystream to save the bitmap
- Use TCP socket to send the bitmap serialized
To Recive:
- Receive the message with readbytes method
- Use memorystream to store the byte array
- Use
Image.FromStream(memorystream)to create a image
It works nice on LAN connection but when I connect with a remote server using VPN, the image takes 0.5 to 5 seconds to arrive
this is my code:
DeskTop Class:
internal static class Desktop
{
public static Image TakeScreenShoot()
{
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
try
{
using (Graphics Graphics = Graphics.FromImage(bitmap))
{
Graphics.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
}
}
catch
{
bitmap = null;
}
return bitmap;
}
public static void SerializeScreen(Stream stream, Image Image)
{
MemoryStream memory = new MemoryStream();
Image.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
int numBytes = (int)memory.Length;
BinaryWriter binaryWriter = new BinaryWriter(stream);
binaryWriter.Write(numBytes);
binaryWriter.Write(memory.GetBuffer(), 0, numBytes);
stream.Flush()
}
public static Image DeserializeScreen(Stream stream)
{
BinaryReader binaryReader = new BinaryReader(stream);
int numBytes = binaryReader.ReadInt32();
byte[] buffer = binaryReader.ReadBytes(numBytes);
MemoryStream memory = new MemoryStream(buffer);
return Image.FromStream(memory);
}
}
Host class
private void SendImage()
{
while (Status == ServerStatus.Connected)
{
try
{
Image bitmap = Desktop.TakeScreenShoot();
Desktop.SerializeScreen(_NetStream,bitmap);
}
catch
{
}
}
}
Client Class
protected void ReciveMessage()
{
while(Status == ServerStatus.Connected)
{
try
{
ImageRecibed?.Invoke(Desktop.DeserializeScreen(_NetStream));
}
catch
{
}
}
}
How can I improve my code to run faster?
here a Video of the application speed
PD. I'm so new on this