[C#] C#通过Socket在网络间发送和接收图片的演示代码 →→→→→进入此内容的聊天室

来自 , 2020-02-27, 写在 C#, 查看 113 次.
URL http://www.code666.cn/view/dcb8f45f
  1.  using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.Sockets;
  5. using System.Net;
  6. using System.IO;
  7.  
  8. namespace ConsoleApplication1
  9. {
  10.     Class Program
  11.     {
  12.         static void Main (String[] args)
  13.         {
  14.             // 1. to create a socket
  15.             Socket sListen = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  16.  
  17.             // 2. Fill IP
  18.             IPAddress IP = IPAddress.Parse ("127.0.0.1");
  19.             IPEndPoint IPE = new IPEndPoint (IP, 4321);
  20.  
  21.             // 3. binding
  22.             sListen.Bind (IPE);
  23.  
  24.             // 4. Monitor
  25.             Console.WriteLine ("Service is listening ...");
  26.             sListen.Listen (2);
  27.  
  28.             // 5. loop to accept client connection requests
  29.             while (true)
  30.             {
  31.                 Socket clientSocket;
  32.                 try
  33.                 {
  34.                     clientSocket = sListen.Accept ();
  35.                 }
  36.                 catch
  37.                 {
  38.                     throw;
  39.                 }
  40.  
  41.                 // send data to the client
  42.                 //clientSocket.Send (Encoding.Unicode.GetBytes ("I am a server, you there?? !!!!"));
  43.  
  44.                 // send the file
  45.                 byte[] buffer = ReadImageFile ("1.jpg");
  46.                 clientSocket.Send (buffer, buffer.Length, SocketFlags.None);
  47.                 Console.WriteLine ("Send success!");
  48.             }
  49.         }
  50.  
  51.         private static byte[] ReadImageFile (String img)
  52.         {
  53.             FileInfo fileinfo = new FileInfo (img);
  54.             byte[] buf = new byte[fileInfo.Length];
  55.             FileStream fs = new FileStream (img, FileMode.Open, FileAccess.Read);
  56.             fs.Read (buf, 0, buf.Length);
  57.             fs.Close ();
  58.             //fileInfo.Delete ();
  59.             GC.ReRegisterForFinalize (fileinfo);
  60.             GC.ReRegisterForFinalize (fs);
  61.             return buf;
  62.         }
  63.  
  64.     }
  65. }
  66.  
  67.  
  68.  
  69. //csharp/7780

回复 "C#通过Socket在网络间发送和接收图片的演示代码"

这儿你可以回复上面这条便签

captcha