C#对Socket操作的封装

原创
小哥 2年前 (2023-05-25) 阅读数 7 #大杂烩

转自: http://www.cnblogs.com/shengshuai/archive/2006/10/14/socket.html

using System;
using System.Net ;
using System.Net.Sockets ;
using System.IO ;
using LogDll;

namespace NetDll
{
    /** 
    /// Net : 提供静态方法来封装常用的网络操作
    /// 
    public sealed class Net
    {
       private Net(){
      }

       /** 
       /// 连接使用 tcp 协议服务器
       /// 
       /// 服务端的ip地址
       /// 服务器的端口号
       /// 
      public static Socket ConnectServer( string ip ,int port ) {
            Socket s = null;

            try {
                IPAddress ipAddress = IPAddress.Parse ( ip );
                IPEndPoint ipEndPoint = new IPEndPoint ( ipAddress,port );
                s = new Socket ( ipEndPoint.AddressFamily ,SocketType.Stream ,ProtocolType.Tcp );
                s.Connect ( ipEndPoint );
                if ( s.Connected== false ) {
                    s = null;
                }
            }
            catch ( Exception e ) {
                Log.WriteLog ( e );
            }
            return s;
        }

        /** 
        /// 用主机名称连接使用Tcp协议服务器
        /// 
        /// 在hosts 文件中存在的主机名
        /// 服务器的端口号
        /// 
        public static Socket ConnectServByHostName( string hostName,int port ){
            Socket s = null;
            IPHostEntry iphe = null;

            try {
                iphe = Dns.Resolve ( hostName );            
                foreach ( IPAddress ipad in iphe.AddressList ) {
                    IPEndPoint ipe = new IPEndPoint (ipad,port);
                    Socket tmps = new Socket (ipe.AddressFamily ,SocketType.Stream ,ProtocolType.Tcp );
                    tmps.Connect ( ipe );

                    if ( tmps.Connected ) {
                        s = tmps;
                        break;
                    }
                    else
                        continue;
                }                
            }
            catch ( Exception e ) {
                Log.WriteLog ( e );
            }
            return s;
        }

        /** 
        /// 将数据发送到远程主机
        /// 
        /// 发送已连接到远程主机的数据 Socket
        /// 要发送的数据
        /// 发送数据的超时时间(以秒为单位),可以精确到微秒
        /// 0:成功发送数据;-1:超时;-2:发送数据时出错;-3:发送数据时发生异常
        /// 
        /// 当 outTime 指定为-1将等到有数据要发送
        /// 
        public static int SendData ( Socket socket,byte[] buffer,int outTime ) {
            if ( socket == null ||socket.Connected == false ) {
                throw new ArgumentException ("参数socket 为null或未连接到远程计算机");
            }
            if ( buffer == null || buffer.Length == 0 ) {
                throw new ArgumentException ("参数buffer 为null ,或者长度是 0");
            }

            int flag = 0;
            try {
                int left = buffer.Length ;
                int sndLen  = 0;

                while ( true ) {
                    if ( ( socket.Poll (outTime*1000000,SelectMode.SelectWrite ) == true ) ) {        // 收集足够的传出数据后开始发送
                        sndLen = socket.Send (buffer,sndLen ,left ,SocketFlags.None );
                        left -= sndLen ;
                        if ( left == 0 ) {                                        // 所有数据均已发送
                          flag = 0;
                          break;
                      }
                      else {
                           if ( sndLen > 0 ) {                                    // 数据部分已发送
                                continue;
                            }
                            else {                                                // 发送数据时出错
                                flag = -2;
                                break;
                            }
                        }                        
                    }
                    else {                                                        // 超时退出
                       flag = -1;
                        break;
                    }
                }
            }
            catch ( SocketException e ) {
                Log.WriteLog ( e );
                flag = -3;
            }
            return flag;
        }

        /** 
        /// 将数据发送到远程主机
        /// 
        /// 发送已连接到远程主机的数据 Socket
        /// 要发送的字符串
        /// 发送数据的超时时间(以秒为单位),可以精确到微秒
        /// 0:成功发送数据;-1:超时;-2:发送数据时出错;-3:发送数据时发生异常
        /// 
        /// 当 outTime 指定为-1将等到有数据要发送
        /// 
        public static int SendData ( Socket socket,string buffer,int outTime ) {
            if ( buffer == null || buffer.Length == 0 ) {
                throw new ArgumentException ("要发送的字符串长度不能为零.");
            }
            return  ( SendData ( socket,System.Text .Encoding .Default .GetBytes ( buffer ),outTime) );
        }

        /** 
        /// 接收远程主机发送的数据
        /// 
        /// 接收数据并已连接到远程主机 socket
        /// 用于接收数据的缓冲区
        /// 接收数据的超时时间,以秒为单位,可以精确到微秒
       /// 0:成功接收数据;-1:超时;-2:接收数据时出错;-3:接收数据时出现异常
       /// 
       /// 1、当 outTime 指定为-1等到有要接收的数据;
       /// 2要接收的数据长度,由下式确定 buffer 长度由以下因素决定。
       /// 
       public static int RecvData ( Socket socket,byte[] buffer ,int outTime ) {
           if ( socket == null || socket.Connected == false ) {
               throw new ArgumentException ("参数socket 为null或未连接到远程计算机");
            }
            if ( buffer == null || buffer.Length == 0 ) {
                throw new ArgumentException ("参数buffer 为null ,或者长度是 0");
            }
            buffer.Initialize ();
            int left = buffer.Length ;
            int curRcv = 0;
            int flag = 0;

            try {
                while ( true ) {
                    if ( socket.Poll (outTime*1000000,SelectMode.SelectRead ) == true ) {        // 已经有数据等待接收
                        curRcv = socket.Receive (buffer,curRcv,left ,SocketFlags.None );
                       left -= curRcv;
                       if ( left == 0 ) {                                    // 已收到所有数据 
                            flag = 0;
                            break;
                        }
                        else {
                            if ( curRcv > 0 ) {                                // 数据已部分接收
                                continue;
                            }
                            else {                                            // 出现错误
                                flag = -2;
                                break;
                            }
                        }
                    }
                    else {                                                    // 超时退出
                        flag = -1;
                        break;
                    }
                }
            }
            catch ( SocketException e ) {
                Log.WriteLog ( e );
                flag = -3;
            }
            return flag;
        }

        /** 
        /// 接收远程主机发送的数据
        /// 
        /// 接收数据并已连接到远程主机 socket
        /// 存储接收数据的字符串
        /// 要接收的数据长度
        /// 接收数据的超时时间,以秒为单位,可以精确到微秒
        /// 0:成功接收数据;-1:超时;-2:接收数据时出错;-3:接收数据时出现异常
        /// 
        /// 当 outTime 指定为-1等到有要接收的数据;
        /// 
        public static int RecvData ( Socket socket,string buffer ,int bufferLen,int outTime ) {
            if ( bufferLen <= 0 ) {
                throw new ArgumentException ("存储待用于接收数据的缓冲区长度必须大于0");
            }

using System;
using System.Net ;
using System.Net.Sockets ;
using System.IO ;
using LogDll;

namespace NetDll
{
    /** 
    /// Net : 提供静态方法来封装常用的网络操作
    /// 
    public sealed class Net
    {
       private Net(){
      }

       /** 
       /// 连接使用 tcp 协议服务器
       /// 
       /// 服务端的ip地址
       /// 服务器的端口号
       /// 
      public static Socket ConnectServer( string ip ,int port ) {
            Socket s = null;

            try {
                IPAddress ipAddress = IPAddress.Parse ( ip );
                IPEndPoint ipEndPoint = new IPEndPoint ( ipAddress,port );
                s = new Socket ( ipEndPoint.AddressFamily ,SocketType.Stream ,ProtocolType.Tcp );
                s.Connect ( ipEndPoint );
                if ( s.Connected== false ) {
                    s = null;
                }
            }
            catch ( Exception e ) {
                Log.WriteLog ( e );
            }
            return s;
        }

        /** 
        /// 用主机名称连接使用Tcp协议服务器
        /// 
        /// 在hosts 文件中存在的主机名
        /// 服务器的端口号
        /// 
        public static Socket ConnectServByHostName( string hostName,int port ){
            Socket s = null;
            IPHostEntry iphe = null;

            try {
                iphe = Dns.Resolve ( hostName );            
                foreach ( IPAddress ipad in iphe.AddressList ) {
                    IPEndPoint ipe = new IPEndPoint (ipad,port);
                    Socket tmps = new Socket (ipe.AddressFamily ,SocketType.Stream ,ProtocolType.Tcp );
                    tmps.Connect ( ipe );

                    if ( tmps.Connected ) {
                        s = tmps;
                        break;
                    }
                    else
                        continue;
                }                
            }
            catch ( Exception e ) {
                Log.WriteLog ( e );
            }
            return s;
        }

        /** 
        /// 将数据发送到远程主机
        /// 
        /// 发送已连接到远程主机的数据 Socket
        /// 要发送的数据
        /// 发送数据的超时时间(以秒为单位),可以精确到微秒
        /// 0:成功发送数据;-1:超时;-2:发送数据时出错;-3:发送数据时发生异常
        /// 
        /// 当 outTime 指定为-1将等到有数据要发送
        /// 
        public static int SendData ( Socket socket,byte[] buffer,int outTime ) {
            if ( socket == null ||socket.Connected == false ) {
                throw new ArgumentException ("参数socket 为null或未连接到远程计算机");
            }
            if ( buffer == null || buffer.Length == 0 ) {
                throw new ArgumentException ("参数buffer 为null ,或者长度是 0");
            }

            int flag = 0;
            try {
                int left = buffer.Length ;
                int sndLen  = 0;

                while ( true ) {
                    if ( ( socket.Poll (outTime*1000000,SelectMode.SelectWrite ) == true ) ) {        // 收集足够的传出数据后开始发送
                        sndLen = socket.Send (buffer,sndLen ,left ,SocketFlags.None );
                        left -= sndLen ;
                        if ( left == 0 ) {                                        // 所有数据均已发送
                          flag = 0;
                          break;
                      }
                      else {
                           if ( sndLen > 0 ) {                                    // 数据部分已发送
                                continue;
                            }
                            else {                                                // 发送数据时出错
                                flag = -2;
                                break;
                            }
                        }                        
                    }
                    else {                                                        // 超时退出
                       flag = -1;
                        break;
                    }
                }
            }
            catch ( SocketException e ) {
                Log.WriteLog ( e );
                flag = -3;
            }
            return flag;
        }

        /** 
        /// 将数据发送到远程主机
        /// 
        /// 发送已连接到远程主机的数据 Socket
        /// 要发送的字符串
        /// 发送数据的超时时间(以秒为单位),可以精确到微秒
        /// 0:成功发送数据;-1:超时;-2:发送数据时出错;-3:发送数据时发生异常
        /// 
        /// 当 outTime 指定为-1将等到有数据要发送
        /// 
        public static int SendData ( Socket socket,string buffer,int outTime ) {
            if ( buffer == null || buffer.Length == 0 ) {
                throw new ArgumentException ("要发送的字符串长度不能为零.");
            }
            return  ( SendData ( socket,System.Text .Encoding .Default .GetBytes ( buffer ),outTime) );
        }

        /** 
        /// 接收远程主机发送的数据
        /// 
        /// 接收数据并已连接到远程主机 socket
        /// 用于接收数据的缓冲区
        /// 接收数据的超时时间,以秒为单位,可以精确到微秒
       /// 0:成功接收数据;-1:超时;-2:接收数据时出错;-3:接收数据时出现异常
       /// 
       /// 1、当 outTime 指定为-1等到有要接收的数据;
       /// 2要接收的数据长度,由下式确定 buffer 长度由以下因素决定。
       /// 
       public static int RecvData ( Socket socket,byte[] buffer ,int outTime ) {
           if ( socket == null || socket.Connected == false ) {
               throw new ArgumentException ("参数socket 为null或未连接到远程计算机");
            }
            if ( buffer == null || buffer.Length == 0 ) {
                throw new ArgumentException ("参数buffer 为null ,或者长度是 0");
            }
            buffer.Initialize ();
            int left = buffer.Length ;
            int curRcv = 0;
            int flag = 0;

            try {
                while ( true ) {
                    if ( socket.Poll (outTime*1000000,SelectMode.SelectRead ) == true ) {        // 已经有数据等待接收
                        curRcv = socket.Receive (buffer,curRcv,left ,SocketFlags.None );
                       left -= curRcv;
                       if ( left == 0 ) {                                    // 已收到所有数据 
                            flag = 0;
                            break;
                        }
                        else {
                            if ( curRcv > 0 ) {                                // 数据已部分接收
                                continue;
                            }
                            else {                                            // 出现错误
                                flag = -2;
                                break;
                            }
                        }
                    }
                    else {                                                    // 超时退出
                        flag = -1;
                        break;
                    }
                }
            }
            catch ( SocketException e ) {
                Log.WriteLog ( e );
                flag = -3;
            }
            return flag;
        }

        /** 
        /// 接收远程主机发送的数据
        /// 
        /// 接收数据并已连接到远程主机 socket
        /// 存储接收数据的字符串
        /// 要接收的数据长度
        /// 接收数据的超时时间,以秒为单位,可以精确到微秒
        /// 0:成功接收数据;-1:超时;-2:接收数据时出错;-3:接收数据时出现异常
        /// 
        /// 当 outTime 指定为-1等到有要接收的数据;
        /// 
        public static int RecvData ( Socket socket,string buffer ,int bufferLen,int outTime ) {
            if ( bufferLen <= 0 ) {
                throw new ArgumentException ("存储待用于接收数据的缓冲区长度必须大于0");
            }
            byte[] tmp = new byte [ bufferLen ];
            int flag = 0;
            if ( ( flag = RecvData ( socket,tmp,outTime)) == 0) {
                buffer = System.Text.Encoding .Default .GetString ( tmp );
            }
            return flag;
        }

        /** 
        /// 将文件发送到远程主机
        /// 
        /// 发送已连接到远程主机的数据 socket
        /// 要发送的文件的名称
        /// 发送文件时的缓冲区大小
        /// 在缓冲区中发送数据的超时
        /// 0:已成功发送文件;-1:超时;-2:发送文件时出错;-3:文件发送异常;-4:读取挂起的文件时出错
      /// 
      /// 当 outTime 指定为-1将等到有数据要发送
      /// 
      public static int SendFile ( Socket socket ,string fileName,int maxBufferLength,int outTime ) {
           if ( fileName == null || maxBufferLength <= 0 ) {
               throw new ArgumentException ("要发送的文件的名称为空或发送缓冲区的大小设置不正确.");
            }

            int flag = 0;
            try {
                FileStream fs = new FileStream ( fileName,FileMode.Open ,FileAccess.Read );
                long fileLen = fs.Length ;                        // 文件长度
                long leftLen = fileLen;                            // 未读部分
                int readLen = 0;                                // 阅读部分
                byte[] buffer = null;

                if ( fileLen <= maxBufferLength ) {            /**//* 可以一次读取文件*/
                   buffer = new byte [ fileLen ];
                   readLen = fs.Read (buffer,0,(int )fileLen );
                   flag = SendData( socket,buffer,outTime );
               }
               else {                                    /**//* 循环读取文件,并发送 */                    
                    buffer = new byte[ maxBufferLength ];
                    while ( leftLen != 0 ) {                    
                        readLen = fs.Read (buffer,0,maxBufferLength );
                        if ( (flag = SendData( socket,buffer,outTime ) ) < 0 ) {
                            break;
                        }
                        leftLen -= readLen;
                    }
                }
                fs.Close ();
            }
            catch ( IOException e ) {
                Log.WriteLog ( e );
                flag = -4;
            }
            return flag;
        }

        /** 
        /// 将文件发送到远程主机
        /// 
        /// 发送已连接到远程主机的数据 socket
        /// 要发送的文件的名称
        /// 0:已成功发送文件;-1:超时;-2:发送文件时出错;-3:文件发送异常;-4:读取挂起的文件时出错
        public static int SendFile ( Socket socket ,string fileName ) {
            return SendFile ( socket,fileName,2048,1 );
        }

        /** 
        /// 接收远程主机发送的文件
        /// 
        /// 要接收且已连接到远程主机的数据 socket
        /// 保存接收数据的文件名
        /// 要接收的文件的长度
        /// 接收文件时的最大缓冲区大小
        /// 接收缓冲区数据的超时
        /// 0:已成功接收文件;-1:超时;-2:接收文件时出错;-3:接收文件时出现异常;-4:写入接收文件时出错
        /// 
        /// 当 outTime 指定为-1等到有要接收的数据
        /// 
        public static int RecvFile ( Socket socket ,string fileName,long fileLength,int maxBufferLength,int outTime ) {
           if ( fileName == null || maxBufferLength <= 0 ) {
               throw new ArgumentException ("用于保存接收数据的文件名为空或发送缓冲区的大小设置不正确.");
            }

            int flag = 0;
            try {
                FileStream fs = new FileStream (fileName,FileMode.Create);
                byte []  buffer = null;

                if ( fileLength <= maxBufferLength ) {                /**//* 一次读取传输的文件 */
                    buffer = new byte [ fileLength ];
                    if ( ( flag =RecvData(socket,buffer,outTime ) ) == 0 ) {
                        fs.Write ( buffer,0,(int)fileLength);
                    }
                }
                else {                                        /**//* 循环读取网络数据并写入文件 */
                    int rcvLen = maxBufferLength;
                    long leftLen = fileLength;                        //剩余未写入的数据
                    buffer = new byte [ rcvLen ];

                    while (  leftLen != 0 ) {                        
                        if ( ( flag =RecvData(socket,buffer,outTime ) ) < 0 ) {
                            break;
                        }
                        fs.Write (buffer,0,rcvLen );
                        leftLen -= rcvLen;                        
                        rcvLen  = ( maxBufferLength < leftLen ) ? maxBufferLength :((int) leftLen) ;
                   }
               }
               fs.Close ();
           }
           catch ( IOException e ) {
               Log.WriteLog ( e );
               flag = -4;
           }
           return flag;
       }

       /** 
       /// 接收远程主机发送的文件
       /// 
       /// 要接收且已连接到远程主机的数据 socket
       /// 保存接收数据的文件名
       /// 要接收的文件的长度
       /// 0:已成功接收文件;-1:超时;-2:接收文件时出错;-3:接收文件时出现异常;-4:写入接收文件时出错
        public static int RecvFile ( Socket socket,string fileName,long fileLength ) {
            return RecvFile ( socket,fileName,fileLength,2048,1);
        }
    }
}

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除