Передача изображения от сервера к клиенту - C#
Формулировка задачи:
Сервер:
Клиент:
В общем нужно передать скриншот экрана с сервера на клиент в сервере как мне кажется я сделал все правильно, но вот вопрос как принять потом этот скриншот на клиенте?
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using System.IO;
- using System.Net;
- using System.Collections;
- using System.Net.Sockets;
- using System.Threading;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.Diagnostics;
- using System.Runtime.Serialization.Formatters.Binary;
- namespace Broadcast_Server
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- public SynchronizationContext uiContext;
- public MainWindow()
- {
- InitializeComponent();
- uiContext = SynchronizationContext.Current;
- Accept();
- }
- private Bitmap TakeScreenShot(System.Windows.Forms.Screen currentScreen)
- {
- Bitmap bmpScreenShot = new Bitmap(currentScreen.Bounds.Width, currentScreen.Bounds.Height,
- System.Drawing.Imaging.PixelFormat.Format32bppArgb);
- Graphics gScreenShot = Graphics.FromImage(bmpScreenShot);
- gScreenShot.CopyFromScreen(currentScreen.Bounds.X, currentScreen.Bounds.Y, 0, 0, currentScreen.Bounds.Size,
- CopyPixelOperation.SourceCopy);
- return bmpScreenShot;
- }
- private async void Receive(Socket handler)
- {
- await Task.Run(() =>
- {
- try
- {
- string client = null;
- string data = null;
- byte[] bytes = new byte[1024];
- // Получим от клиента DNS-имя хоста.
- // Метод Receive получает данные от сокета и заполняет массив байтов, переданный в качестве аргумента
- int bytesRec = handler.Receive(bytes); // Возвращает фактически считанное число байтов
- client = Encoding.Default.GetString(bytes, 0, bytesRec); // конвертируем массив байтов в строку
- client += "(" + handler.RemoteEndPoint.ToString() + ")";
- while (true)
- {
- Bitmap bmp = TakeScreenShot(System.Windows.Forms.Screen.PrimaryScreen);
- MemoryStream memstream = new MemoryStream();
- bmp.Save(memstream, ImageFormat.Bmp);
- byte[] bitmapData = memstream.ToArray();
- if (bitmapData.Length > 1)
- {
- MessageBox.Show(bitmapData.Length + "_Сервер");
- handler.Send(BitConverter.GetBytes(bitmapData.Length));
- handler.Receive(bytes);
- handler.Send(bitmapData);
- Thread.Sleep(800);
- memstream.Dispose();
- }
- }
- string theReply = "Я завершаю обработку сообщений";
- byte[] msg = Encoding.Default.GetBytes(theReply); // конвертируем строку в массив байтов
- handler.Send(msg); // отправляем клиенту сообщение
- handler.Shutdown(SocketShutdown.Both); // Блокируем передачу и получение данных для объекта Socket.
- handler.Close(); // закрываем сокет
- }
- catch (Exception ex)
- {
- MessageBox.Show("Сервер: " + ex.Message);
- }
- });
- }
- private async void Accept()
- {
- await Task.Run(() =>
- {
- try
- {
- IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 49152);
- Socket sListener = new Socket(AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp );
- sListener.Bind(ipEndPoint);
- sListener.Listen(10);
- while (true)
- {
- Socket handler = sListener.Accept();
- Receive(handler);
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show("Сервер: " + ex.Message);
- }
- });
- }
- }
- }
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Net;
- using System.IO;
- using System.Net.Sockets;
- using System.Windows.Shapes;
- using System.Windows.Threading;
- using System.Threading;
- using System.Collections;
- using System.Diagnostics;
- using System.Drawing;
- using System.Runtime.Serialization.Formatters.Binary;
- namespace Broadcast_Client
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- string ip = null;
- IPHostEntry ipHost;
- IPAddress ipAddr;
- IPEndPoint ipEndPoint;
- Socket sock;
- public SynchronizationContext uiContext;
- public MainWindow()
- {
- InitializeComponent();
- }
- private async void Connect()
- {
- await Task.Run(() =>
- {
- try
- {
- ipAddr = IPAddress.Parse(ip);
- ipEndPoint = new IPEndPoint(ipAddr, 49152);
- sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- sock.Connect(ipEndPoint);
- byte[] msg = Encoding.Default.GetBytes(Dns.GetHostName());
- int bytesSent = sock.Send(msg);
- MessageBox.Show("Клиент " + Dns.GetHostName() + " установил соединение с " + sock.RemoteEndPoint.ToString());
- while (true)
- {
- byte[] data = new byte[1024];
- sock.Receive(data);
- MemoryStream memstream = new MemoryStream(data);
- BitmapImage bi = new BitmapImage();
- bi.BeginInit();
- bi.StreamSource = memstream;
- bi.EndInit();
- Dispatcher.Invoke(DispatcherPriority.Normal,
- (ThreadStart)delegate
- {
- pb.Source = bi;
- });
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show("Клиент: " + ex.Message);
- }
- });
- }
- private void Connect_Click(object sender, RoutedEventArgs e)
- {
- ip = ip_address.Text;
- Connect();
- }
- }
- }
Что ни у кого нет идей?
+++
Решение задачи: «Передача изображения от сервера к клиенту»
textual
Листинг программы
- byte[] data = new byte[100000];
- sock.Receive(data);
- MemoryStream memstream = new MemoryStream(data);
- BitmapImage bi = new BitmapImage();
- bi.BeginInit();
- bi.StreamSource = memstream; //преобразую в Image конвертируя его в System.Windows.Control.Image
- bi.EndInit();
- Dispatcher.Invoke(DispatcherPriority.Normal,
- (ThreadStart)delegate
- {
- pb.Source = bi;
- });
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д