Here's a reasonably complete (albeit quick and dirty) solution:
Server:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace ImageServer
{
static class Program
{
static void Main()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Any, 23456));
socket.Listen(100);
while (true)
{
using (var client = socket.Accept())
{
var bounds = Screen.PrimaryScreen.Bounds;
var bitmap = new Bitmap(bounds.Width, bounds.Height);
try
{
while (true)
{
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(bounds.X, 0, bounds.Y, 0, bounds.Size);
}
byte[] imageData;
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png);
imageData = stream.ToArray();
}
var lengthData = BitConverter.GetBytes(imageData.Length);
if (client.Send(lengthData) < lengthData.Length) break;
if (client.Send(imageData) < imageData.Length) break;
Thread.Sleep(1000);
}
}
catch
{
break;
}
}
}
}
}
}
}
Client (a form with a single button: "button1" and a single pictureBox: "pictureBox1"):
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace ImageClient
{
public partial class Form1 : Form
{
private Bitmap _buffer;
public Form1()
{
InitializeComponent();
}
private void Button1Click(object sender, EventArgs e)
{
button1.Enabled = false;
ThreadPool.QueueUserWorkItem(GetSnapshots);
}
private void GetSnapshots(object state)
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(new IPEndPoint(IPAddress.Loopback, 23456));
while (true)
{
var lengthData = new byte[4];
var lengthBytesRead = 0;
while (lengthBytesRead < lengthData.Length)
{
var read = socket.Receive(lengthData, lengthBytesRead, lengthData.Length - lengthBytesRead, SocketFlags.None);
if (read == 0) return;
lengthBytesRead += read;
}
var length = BitConverter.ToInt32(lengthData, 0);
var imageData = new byte[length];
var imageBytesRead = 0;
while (imageBytesRead < imageData.Length)
{
var read = socket.Receive(imageData, imageBytesRead, imageData.Length - imageBytesRead, SocketFlags.None);
if (read == 0) return;
imageBytesRead += read;
}
using (var stream = new MemoryStream(imageData))
{
var bitmap = new Bitmap(stream);
Invoke(new ImageCompleteDelegate(ImageComplete), new object[] { bitmap });
}
}
}
}
private delegate void ImageCompleteDelegate(Bitmap bitmap);
private void ImageComplete(Bitmap bitmap)
{
if (_buffer != null)
{
_buffer.Dispose();
}
_buffer = new Bitmap(bitmap);
pictureBox1.Size = _buffer.Size;
pictureBox1.Invalidate();
}
private void PictureBox1Paint(object sender, PaintEventArgs e)
{
if (_buffer == null) return;
e.Graphics.DrawImage(_buffer, 0, 0);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…