Передача изображения от сервера к клиенту - C#

Узнай цену своей работы

Формулировка задачи:

Сервер:
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using System.IO;
  16. using System.Net;
  17. using System.Collections;
  18. using System.Net.Sockets;
  19. using System.Threading;
  20. using System.Drawing;
  21. using System.Drawing.Imaging;
  22. using System.Diagnostics;
  23. using System.Runtime.Serialization.Formatters.Binary;
  24.  
  25. namespace Broadcast_Server
  26. {
  27. /// <summary>
  28. /// Interaction logic for MainWindow.xaml
  29. /// </summary>
  30. public partial class MainWindow : Window
  31. {
  32. public SynchronizationContext uiContext;
  33. public MainWindow()
  34. {
  35. InitializeComponent();
  36. uiContext = SynchronizationContext.Current;
  37. Accept();
  38. }
  39. private Bitmap TakeScreenShot(System.Windows.Forms.Screen currentScreen)
  40. {
  41. Bitmap bmpScreenShot = new Bitmap(currentScreen.Bounds.Width, currentScreen.Bounds.Height,
  42. System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  43. Graphics gScreenShot = Graphics.FromImage(bmpScreenShot);
  44. gScreenShot.CopyFromScreen(currentScreen.Bounds.X, currentScreen.Bounds.Y, 0, 0, currentScreen.Bounds.Size,
  45. CopyPixelOperation.SourceCopy);
  46. return bmpScreenShot;
  47. }
  48. private async void Receive(Socket handler)
  49. {
  50. await Task.Run(() =>
  51. {
  52. try
  53. {
  54. string client = null;
  55. string data = null;
  56. byte[] bytes = new byte[1024];
  57. // Получим от клиента DNS-имя хоста.
  58. // Метод Receive получает данные от сокета и заполняет массив байтов, переданный в качестве аргумента
  59. int bytesRec = handler.Receive(bytes); // Возвращает фактически считанное число байтов
  60. client = Encoding.Default.GetString(bytes, 0, bytesRec); // конвертируем массив байтов в строку
  61. client += "(" + handler.RemoteEndPoint.ToString() + ")";
  62. while (true)
  63. {
  64. Bitmap bmp = TakeScreenShot(System.Windows.Forms.Screen.PrimaryScreen);
  65. MemoryStream memstream = new MemoryStream();
  66. bmp.Save(memstream, ImageFormat.Bmp);
  67. byte[] bitmapData = memstream.ToArray();
  68. if (bitmapData.Length > 1)
  69. {
  70. MessageBox.Show(bitmapData.Length + "_Сервер");
  71. handler.Send(BitConverter.GetBytes(bitmapData.Length));
  72. handler.Receive(bytes);
  73. handler.Send(bitmapData);
  74. Thread.Sleep(800);
  75. memstream.Dispose();
  76. }
  77. }
  78. string theReply = "Я завершаю обработку сообщений";
  79. byte[] msg = Encoding.Default.GetBytes(theReply); // конвертируем строку в массив байтов
  80. handler.Send(msg); // отправляем клиенту сообщение
  81. handler.Shutdown(SocketShutdown.Both); // Блокируем передачу и получение данных для объекта Socket.
  82. handler.Close(); // закрываем сокет
  83. }
  84. catch (Exception ex)
  85. {
  86. MessageBox.Show("Сервер: " + ex.Message);
  87. }
  88. });
  89. }
  90. private async void Accept()
  91. {
  92. await Task.Run(() =>
  93. {
  94. try
  95. {
  96. IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 49152);
  97. Socket sListener = new Socket(AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp );
  98. sListener.Bind(ipEndPoint);
  99. sListener.Listen(10);
  100. while (true)
  101. {
  102. Socket handler = sListener.Accept();
  103. Receive(handler);
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. MessageBox.Show("Сервер: " + ex.Message);
  109. }
  110. });
  111. }
  112. }
  113. }
Клиент:
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Net;
  15. using System.IO;
  16. using System.Net.Sockets;
  17. using System.Windows.Shapes;
  18. using System.Windows.Threading;
  19. using System.Threading;
  20. using System.Collections;
  21. using System.Diagnostics;
  22. using System.Drawing;
  23. using System.Runtime.Serialization.Formatters.Binary;
  24. namespace Broadcast_Client
  25. {
  26. /// <summary>
  27. /// Interaction logic for MainWindow.xaml
  28. /// </summary>
  29. public partial class MainWindow : Window
  30. {
  31. string ip = null;
  32. IPHostEntry ipHost;
  33. IPAddress ipAddr;
  34. IPEndPoint ipEndPoint;
  35. Socket sock;
  36. public SynchronizationContext uiContext;
  37. public MainWindow()
  38. {
  39. InitializeComponent();
  40. }
  41. private async void Connect()
  42. {
  43. await Task.Run(() =>
  44. {
  45. try
  46. {
  47. ipAddr = IPAddress.Parse(ip);
  48. ipEndPoint = new IPEndPoint(ipAddr, 49152);
  49. sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  50. sock.Connect(ipEndPoint);
  51. byte[] msg = Encoding.Default.GetBytes(Dns.GetHostName());
  52. int bytesSent = sock.Send(msg);
  53. MessageBox.Show("Клиент " + Dns.GetHostName() + " установил соединение с " + sock.RemoteEndPoint.ToString());
  54. while (true)
  55. {
  56. byte[] data = new byte[1024];
  57. sock.Receive(data);
  58. MemoryStream memstream = new MemoryStream(data);
  59. BitmapImage bi = new BitmapImage();
  60. bi.BeginInit();
  61. bi.StreamSource = memstream;
  62. bi.EndInit();
  63. Dispatcher.Invoke(DispatcherPriority.Normal,
  64. (ThreadStart)delegate
  65. {
  66. pb.Source = bi;
  67. });
  68. }
  69. }
  70. catch (Exception ex)
  71. {
  72. MessageBox.Show("Клиент: " + ex.Message);
  73. }
  74. });
  75. }
  76.  
  77. private void Connect_Click(object sender, RoutedEventArgs e)
  78. {
  79. ip = ip_address.Text;
  80. Connect();
  81. }
  82.  
  83. }
  84. }
В общем нужно передать скриншот экрана с сервера на клиент в сервере как мне кажется я сделал все правильно, но вот вопрос как принять потом этот скриншот на клиенте?
Что ни у кого нет идей?
+++

Решение задачи: «Передача изображения от сервера к клиенту»

textual
Листинг программы
  1.                         byte[] data = new byte[100000];
  2.                         sock.Receive(data);
  3.                         MemoryStream memstream = new MemoryStream(data);
  4.                         BitmapImage bi = new BitmapImage();
  5.                         bi.BeginInit();
  6.                         bi.StreamSource = memstream; //преобразую в Image конвертируя его в System.Windows.Control.Image
  7.                         bi.EndInit();
  8.                         Dispatcher.Invoke(DispatcherPriority.Normal,
  9.                                     (ThreadStart)delegate
  10.                         {
  11.                            pb.Source = bi;
  12.                         });

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

12   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы