欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#使用Socket实现发送和接收图片的方法

程序员文章站 2023-12-11 18:13:28
本文实例讲述了c#使用socket实现发送和接收图片的方法。分享给大家供大家参考。具体如下: using system; using system.collec...

本文实例讲述了c#使用socket实现发送和接收图片的方法。分享给大家供大家参考。具体如下:

using system;
using system.collections.generic;
using system.text;
using system.net.sockets;
using system.net;
using system.io;
namespace consoleapplication1
{
  class program
  {
    static void main (string[] args)
    {
      // 1. to create a socket
      socket slisten = new socket (addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
      // 2. fill ip
      ipaddress ip = ipaddress.parse ("127.0.0.1");
      ipendpoint ipe = new ipendpoint (ip, 4321);
      // 3. binding
      slisten.bind (ipe);
      // 4. monitor
      console.writeline ("service is listening ...");
      slisten.listen (2);
      // 5. loop to accept client connection requests
      while (true)
      {
        socket clientsocket;
        try
        {
          clientsocket = slisten.accept ();
        }
        catch
        {
          throw;
        }
        // send data to the client
        //clientsocket.send (encoding.unicode.getbytes ("i am a server, you there?? !!!!"));
        // send the file
        byte[] buffer = readimagefile ("1.jpg");
        clientsocket.send (buffer, buffer.length, socketflags.none);
        console.writeline ("send success!");
      }
    }
    private static byte[] readimagefile (string img)
    {
      fileinfo fileinfo = new fileinfo (img);
      byte[] buf = new byte[fileinfo.length];
      filestream fs = new filestream (img, filemode.open, fileaccess.read);
      fs.read (buf, 0, buf.length);
      fs.close ();
      //fileinfo.delete ();
      gc.reregisterforfinalize (fileinfo);
      gc.reregisterforfinalize (fs);
      return buf;
    }
  }
}

客户端接收和保存图片的代码如下:

using system;
using system.collections.generic;
using system.text;
using system.net.sockets;
using system.net;
using system.io;
namespace consoleapplication2
{
  class program
  {
    static void main (string[] args)
    {
      // 1. to create a socket
      socket s = new socket (addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
      // 2. fill in the remote ip
      ipaddress ip = ipaddress.parse ("127.0.0.1");
      ipendpoint ipe = new ipendpoint (ip, 4321);
      console.writeline ("started connection service ....");
      // 3. connect to the server
      s.connect (ipe);
      // 4. receive data
      byte[] buffer = new byte[1000000];
      s.receive (buffer, buffer.length, socketflags.none);
      //var msg = encoding.unicode.getstring (buffer);
      //console.writeline ("received message: (0)", msg);
      console.writeline ("receive success");
      filestream fs = file.create ("1.jpg");
      fs.write (buffer, 0, buffer.length);
      fs.close ();
      console.readkey ();
    }
  }
}

希望本文所述对大家的c#程序设计有所帮助。

上一篇:

下一篇: