SoFunction
Updated on 2025-03-06

C# uses Socket to implement the method of sending and receiving pictures

This article describes the method of using Socket to send and receive pictures. Share it for your reference. The details are as follows:

using System;
using ;
using ;
using ;
using ;
using ;
namespace ConsoleApplication1
{
  Class Program
  {
    static void Main (String[] args)
    {
      // 1. to create a socket
      Socket sListen = new Socket (, , );
      // 2. Fill IP
      IPAddress IP =  ("127.0.0.1");
      IPEndPoint IPE = new IPEndPoint (IP, 4321);
      // 3. binding
       (IPE);
      // 4. Monitor
       ("Service is listening ...");
       (2);
      // 5. loop to accept client connection requests
      while (true)
      {
        Socket clientSocket;
        try
        {
          clientSocket =  ();
        }
        catch
        {
          throw;
        }
        // send data to the client
        // ( ("I am a server, you there?? !!!!"));
        // send the file
        byte[] buffer = ReadImageFile ("");
         (buffer, , );
         ("Send success!");
      }
    }
    private static byte[] ReadImageFile (String img)
    {
      FileInfo fileinfo = new FileInfo (img);
      byte[] buf = new byte[];
      FileStream fs = new FileStream (img, , );
       (buf, 0, );
       ();
      // ();
       (fileinfo);
       (fs);
      return buf;
    }
  }
}

The code for the client to receive and save pictures is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
namespace ConsoleApplication2
{
  Class Program
  {
    static void Main (String[] args)
    {
      // 1. to create a socket
      Socket S = new Socket (, , );
      // 2. fill in the remote IP
      IPAddress IP =  ("127.0.0.1");
      IPEndPoint IPE = new IPEndPoint (IP, 4321);
       ("started connection service ....");
      // 3. connect to the server
       (IPE);
      // 4. receive data
      byte[] buffer = new byte[1000000];
       (buffer, , );
      //var Msg =  (buffer);
      // ("received message: (0)", msg);
       ("Receive success");
      FileStream fs =  ("");
       (buffer, 0, );
       ();
       ();
    }
  }
}

I hope this article will be helpful to everyone's C# programming.