❔ Capture screen(video codec) and send to client simultaneously using socket
I have already made send image code (capture image and send to client continuously. But it causes lag. So i want to try new method.
Code:
Code:
private void Screen()
{
try
{
listener_3.Start();
eventLog1.WriteEntry("Waiting for connection...");
while (true)
{
Socket client = listener_3.AcceptSocket();
Console.WriteLine("Client connected");
while (client.Connected)
{
// Capture the screen
Bitmap screen = CaptureScreen();
int newWidth = screen.Width / 4; // Reduce width by half
int newHeight = screen.Height / 4; // Reduce height by half
Bitmap resizedImage = new Bitmap(newWidth, newHeight);
// Use Graphics.DrawImage to resize the image
using (Graphics graphics = Graphics.FromImage(resizedImage))
{
graphics.DrawImage(screen, 0, 0, newWidth, newHeight);
}
// Convert the resized image to a byte array and send it to the client
byte[] imageData = ImageToByteArray(resizedImage);
client.Send(imageData);
// Delay between sending each frame (adjust as needed)
Thread.Sleep(20);
}
eventLog1.WriteEntry("Connection terminated");
client.Close();
}
}
catch (Exception e)
{
listener_3.Stop();
listener_3 = new TcpListener(IPAddress.Any, 50523);
eventLog1.WriteEntry("Error: " + e.Message);
}
}private void Screen()
{
try
{
listener_3.Start();
eventLog1.WriteEntry("Waiting for connection...");
while (true)
{
Socket client = listener_3.AcceptSocket();
Console.WriteLine("Client connected");
while (client.Connected)
{
// Capture the screen
Bitmap screen = CaptureScreen();
int newWidth = screen.Width / 4; // Reduce width by half
int newHeight = screen.Height / 4; // Reduce height by half
Bitmap resizedImage = new Bitmap(newWidth, newHeight);
// Use Graphics.DrawImage to resize the image
using (Graphics graphics = Graphics.FromImage(resizedImage))
{
graphics.DrawImage(screen, 0, 0, newWidth, newHeight);
}
// Convert the resized image to a byte array and send it to the client
byte[] imageData = ImageToByteArray(resizedImage);
client.Send(imageData);
// Delay between sending each frame (adjust as needed)
Thread.Sleep(20);
}
eventLog1.WriteEntry("Connection terminated");
client.Close();
}
}
catch (Exception e)
{
listener_3.Stop();
listener_3 = new TcpListener(IPAddress.Any, 50523);
eventLog1.WriteEntry("Error: " + e.Message);
}
}