C# Socket实现断点上传文件

public partial class VAV_File_Client
    {
        private string path = "";
        private string strBaseDir = "";
        private string host = "";
        private int port1 = 0;
        private int port2 = 0;
        private int port3 = 0;
        private bool IsXuChuan = false;
        private bool IsFuGai = false;
        private int BackDay = 0;
        private int SIZEBUFFER = 0;

        public VAV_File_Client()
        {
            path = System.Configuration.ConfigurationManager.AppSettings["APPEmailXML"].ToString();
            strBaseDir = System.Configuration.ConfigurationManager.AppSettings["strBaseDir"].ToString();
            host = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
            port1 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port1"].ToString());
            port2 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port2"].ToString());
            port3 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port3"].ToString());
            IsXuChuan = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsXuChuan"].ToString());
            IsFuGai = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsFuGai"].ToString());
            BackDay = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["BackDay"].ToString());
            SIZEBUFFER = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SIZEBUFFER"].ToString());
        }
        /// <summary>
/// 启动
/// </summary>
        public void start()
        {
            try
            {
                GetAllDirList(strBaseDir, BackDay);
                foreach (string pathDir in al)
                {
                    if (pathDir.Contains("\t<目录>"))
                    {
                        string ddddS = pathDir.Substring(pathDir.IndexOf(strBaseDir) + strBaseDir.Length);
                        scoketSend(host, port2, Encoding.UTF8.GetBytes(ddddS));  //传输文件名称
                        sendFlie(host, port1, pathDir, IsXuChuan, IsFuGai);//传输文件
                        continue;
                    }
                    //string fileName = pathDir.Substring(pathDir.LastIndexOf("\\") + 1);
                    string fileName = pathDir.Substring(pathDir.IndexOf(strBaseDir) + strBaseDir.Length);

                    byte[] bs = Encoding.UTF8.GetBytes(fileName);

                    scoketSend(host, port2, bs);  //传输文件名称

                    sendFlie(host, port1, pathDir, IsXuChuan, IsFuGai);//传输文件

                    DelFile(pathDir);
                }
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            Console.WriteLine("end");
        }


        //连接服务器发送数据
        /// <summary>
///
/// </summary>
/// <param name="host"></param>
/// <param name="port">2006</param>
/// <param name="bs"></param>
        private void scoketSend(string host, int port, byte[] bs)
        {

            IPAddress ip = IPAddress.Parse(host);
            //   int port = 2006;
            IPEndPoint ipe = new IPEndPoint(ip, port);
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            c.Connect(ipe);
            c.Send(bs, bs.Length, 0);
            c.Close();
        }
        //连接服务器接收数据
        /// <summary>
///
/// </summary>
/// <param name="host"></param>
/// <param name="port">2006</param>
/// <returns></returns>
        private string scoketReceive(string host, int port)
        {
            IPAddress ip = IPAddress.Parse(host);
            //   int port = 2006;
            IPEndPoint ipe = new IPEndPoint(ip, port);
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            c.Connect(ipe);
            string startStr = "";
            byte[] startBytes = new byte[SIZEBUFFER];
            int bytess;
            bytess = c.Receive(startBytes, startBytes.Length, 0);
            startStr += Encoding.ASCII.GetString(startBytes, 0, bytess);
            c.Close();
            return startStr;
        }
        //传输文件名称
        /// <summary>
///
/// </summary>
/// <param name="path">127.0.0.1</param>
/// <param name="port">2006</param>
        private void sendName(string host, int port, string path)
        {
            //string host = "127.0.0.1";
            IPAddress ip = IPAddress.Parse(host);
            //int port = 2006;
            IPEndPoint ipe = new IPEndPoint(ip, port);
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            c.Connect(ipe);

            string fileName = path.Substring(path.LastIndexOf("\\") + 1);
            //UTF8处理中文
            byte[] bs = Encoding.UTF8.GetBytes(fileName);
            c.Send(bs, bs.Length, 0);
            c.Close();
        }
        //所传输的文件是否续传
        /// <summary>
/// 所传输的文件是否续传
/// </summary>
/// <param name="str"></param>
/// <param name="host">127.0.0.1</param>
/// <param name="port">port = 2007</param>
/// <param name="xuchuan">是否续传</param>
        public void setxc(string str, string host, int port, bool xuchuan)
        {
            IPAddress ip = IPAddress.Parse(host);

            port = 2007;
            IPEndPoint ipe = new IPEndPoint(ip, port);
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            c.Connect(ipe);
            string Str = str;
            byte[] bxc = Encoding.ASCII.GetBytes(Str);
            c.Send(bxc, bxc.Length, 0);
            c.Close();
        }

        //传输文件/// <summary>
        /// <summary>
///
/// </summary>
/// <param name="host">"127.0.0.1"</param>
/// <param name="port">port = 2005;</param>
/// <param name="fileName">带路径的文件名</param>
/// <param name="xuchuan">是否需要续传</param>
/// <param name="cover">是否覆盖</param>
        private void sendFlie(string host, int port, string fileName, bool xuchuan, bool IsFuGai)
        {
            try
            {
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                c.Connect(ipe);//建立于远程主机的链接
//接收服务器返回存在的文件大小
                byte[] startBytes = new byte[SIZEBUFFER];
                string startStr = Encoding.ASCII.GetString(startBytes, 0, c.Receive(startBytes, startBytes.Length, 0));
                //已接受文件长度
                int startSet = int.Parse(startStr);
                byte[] b = new byte[SIZEBUFFER];            //创建文件缓冲区,这里可以认为文件的最大值
                if (fileName.Contains("\t<目录>"))
                {
                    c.Close();        //关闭Socket
                    return;
                }
                FileStream file = File.Open(fileName, FileMode.Open, FileAccess.Read);   //创建文件流
//文件字节总长度
                int fileAllLength = (int)file.Length;
                //文件剩余字节长度
                int fileLast = startSet < fileAllLength ? fileAllLength - startSet : 0;

                int intLength = 0;
                #region  续传
                if (startSet > 0 && startSet < fileAllLength && xuchuan == true)
                {
                    //传输文件是否续传
                    setxc("xc", host, port3, xuchuan);
                    file.Seek(long.Parse(startStr), SeekOrigin.Begin); //移动文件流中的当前指针
                    intLength = int.Parse(startStr);
                    while (fileLast > 0)
                    {
                        int count = file.Read(b, 0, b.Length);
                        int readbytes = count >= b.Length ? b.Length : count;
                        readbytes = c.Send(b, 0, readbytes, SocketFlags.None);
                        Encoding.ASCII.GetString(startBytes, 0, c.Receive(startBytes, startBytes.Length, 0));
                        fileLast -= count;
                        intLength += count;
                        file.Seek(intLength, SeekOrigin.Begin);
                        if (fileLast == 0)
                        {
                            c.Send(Encoding.UTF8.GetBytes("end"), Encoding.UTF8.GetBytes("end").Length, 0);
                        }
                    }
                }
                #endregion
                #region
                else
                {
                    if (fileLast == 0 && IsFuGai == false)
                    {
                        setxc("qx", host, port3, xuchuan);
                    }
                    else
                    {
                        //传输文件是否续传
                        setxc("bxc", host, port3, xuchuan);

                        while (fileLast > 0)
                        {
                            int count = file.Read(b, 0, b.Length);
                            int SdCount = fileLast < b.Length ? count : b.Length;
                            SdCount = c.Send(b, 0, SdCount, SocketFlags.None);
                            Encoding.ASCII.GetString(startBytes, 0, c.Receive(startBytes, startBytes.Length, 0));
                            fileLast -= count;//剩余的字节长度
                            intLength += count;//定位指针用
                            file.Seek(intLength, SeekOrigin.Begin);
                            if (fileLast == 0)
                            {
                                c.Send(Encoding.UTF8.GetBytes("end"), Encoding.UTF8.GetBytes("end").Length, 0);
                            }
                            Console.WriteLine("已传送字节:  " + intLength);
                        }
                    }
                }
                #endregion
                file.Close();     //关闭文件流
                string recvStr = "";
                byte[] recvBytes = new byte[SIZEBUFFER];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                //MessageBox.Show(recvStr);
                Console.WriteLine(recvStr);
                c.Close();        //关闭Socket
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("{0}", e);
            }
        }

        public ArrayList al = new ArrayList();//定义存储文件和文件夹名的数组
        public int aaa = 0;//定义标志位参数,递归时判断该参数,若不为0则非第一次递归
        /// <summary>
/// 获取指定某一天之前的文件,不包括当天
/// </summary>
/// <param name="strBaseDir">指定目录</param>
/// <param name="Day">指定天数</param>
        public void GetAllDirList(string strBaseDir, int Day)
        {
            DirectoryInfo di = new DirectoryInfo(strBaseDir);
            DirectoryInfo[] diA = di.GetDirectories();
            if (aaa == 0)
            {
                FileInfo[] fis2 = di.GetFiles();   //有关目录下的文件  
                for (int i2 = 0; i2 < fis2.Length; i2++)
                {

                    if (fis2[i2].CreationTime < DateTime.Now.AddDays(Day) && fis2[i2].FullName.Substring(fis2[i2].FullName.LastIndexOf("\\") + 1).StartsWith("DEL_") == false)//指定时间
                    {
                        al.Add(fis2[i2].FullName);
                    }
                }
            }
            for (int i = 0; i < diA.Length; i++)
            {
                aaa++;
                al.Add(diA[i].FullName + "\t<目录>");
                //diA[i].FullName是某个子目录的绝对地址,把它记录在ArrayList中
                DirectoryInfo di1 = new DirectoryInfo(diA[i].FullName);
                DirectoryInfo[] diA1 = di1.GetDirectories();
                FileInfo[] fis1 = di1.GetFiles();   //有关目录下的文件  
                for (int ii = 0; ii < fis1.Length; ii++)
                {
                    if (fis1[ii].CreationTime < DateTime.Now.AddDays(Day) && fis1[ii].FullName.Substring(fis1[ii].FullName.LastIndexOf("\\") + 1).StartsWith("DEL_") == false)
                    {
                        al.Add(fis1[ii].FullName);
                    }
                }
                GetAllDirList(diA[i].FullName, Day);
            }
        }

        /// <summary>
/// 删除文件
/// </summary>
/// <param name="FileName">文件名</param>
        public void DelFile(string FileName)
        {
            FileInfo fInfo = new FileInfo(FileName);

            fInfo.MoveTo(FileName.Replace(FileName.Substring(FileName.LastIndexOf("\\") + 1), "DEL_" + FileName.Substring(FileName.LastIndexOf("\\") + 1)));
        }

        private void DeleteInDir(string szDirPath)
        {
            if (szDirPath.Trim() == "" || !Directory.Exists(szDirPath))
                return;
            DirectoryInfo dirInfo = new DirectoryInfo(szDirPath);

            FileInfo[] fileInfos = dirInfo.GetFiles();
            if (fileInfos != null && fileInfos.Length > 0)
            {
                foreach (FileInfo fileInfo in fileInfos)
                {

                }
            }

            DirectoryInfo[] dirInfos = dirInfo.GetDirectories();
            if (dirInfos != null && dirInfos.Length > 0)
            {
                foreach (DirectoryInfo childDirInfo in dirInfos)
                {
                    DeleteInDir(childDirInfo.ToString()); //递归
                }
            }
        }
    }

 

 

 

public partial class VAV_File_Server
    {
        private string PathFiles = "";
        private string host = "";
        private int port1 = 0;
        private int port2 = 0;
        private int port3 = 0;
        private bool IsXuChuan = false;
        private bool IsFuGai = false;
        private int SIZEBUFFER = 0;

        /// <summary>
/// 构造函数
/// </summary>
        public VAV_File_Server()
        {
            //path = System.Configuration.ConfigurationManager.AppSettings["APPEmailXML"].ToString();
            PathFiles = System.Configuration.ConfigurationManager.AppSettings["PathFiles"].ToString();
            host = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
            port1 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port1"].ToString());
            port2 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port2"].ToString());
            port3 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["port3"].ToString());
            IsXuChuan = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsXuChuan"].ToString());
            IsFuGai = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsFuGai"].ToString());
            SIZEBUFFER = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SIZEBUFFER"].ToString());
        }
        Socket s;
        Socket s1;
        Socket s2;
        FileStream file;

        public void start()
        {

            #region
            try
            {
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe1 = new IPEndPoint(ip, port1);
                IPEndPoint ipe2 = new IPEndPoint(ip, port2);
                IPEndPoint ipe3 = new IPEndPoint(ip, port3);
                //创建Socket   实例  
                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s1.Bind(ipe1);
                s.Bind(ipe2);
                s2.Bind(ipe3);
                s.Listen(0);
                s1.Listen(0);
                s2.Listen(0);
                while (true)
                {
                    get();
                }
                s.Dispose();
                s1.Dispose();
                s2.Dispose();

            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);

            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            // Console.ReadLine();
            #endregion
        }

        private void get()
        {
            try
            {
                while (true)
                {
                    //获取Socket连接
                    Console.WriteLine("等待接收2006发来的数据");
                    Socket ss = s.Accept();

                    Console.WriteLine("收到2006的数据");
                    Console.WriteLine("等待接收2005发来的数据");
                    Socket ss1 = s1.Accept();
                    Console.WriteLine("收到2005的数据");

                    //接收的文件名称
                    string recvStr = "";
                    if (ss.Connected)             //确定连接
                    {
                        byte[] recvBytes = new byte[SIZEBUFFER];
                        int bytes;
                        bytes = ss.Receive(recvBytes, recvBytes.Length, 0);
                        //UTF8处理中文
                        recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
                        ss.Close();
                    }
                    string path = "";

                    path = @PathFiles.EndsWith("\\") ? PathFiles + Regex.Replace(recvStr, @"^\\", "") : PathFiles + "\\" + Regex.Replace(recvStr, @"^\\", ""); //存放接收的文件路径
                    if (path.Contains("\t<目录>"))//D:\\Down\\第一层\t<目录>
                    {
                        path = path.Replace("\t<目录>", "");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        ss1.Send(Encoding.ASCII.GetBytes("0"), Encoding.ASCII.GetBytes("0").Length, 0);
                        continue;
                    }
                    long lStartPos = 0;
                    if (File.Exists(path))
                    {
                        file = File.OpenWrite(path);
                        lStartPos = file.Length;
                    }
                    else
                    {
                        file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); //写入文件流
//file = new FileStream(path, FileMode.Create); //写入文件流
                        lStartPos = 0;
                    }

                    string startStr = lStartPos.ToString();
                    byte[] bstar = Encoding.ASCII.GetBytes(startStr);
                    ss1.Send(bstar, bstar.Length, 0);

                    if (ss1.Connected)             //确定连接
                    {
                        Console.WriteLine("2005连接成功");
                        //接收文件是否续传
                        Console.WriteLine("2007接受文件是否续传");
                        Socket ss2 = s2.Accept();
                        string str = "";
                        if (ss2.Connected)             //确定连接
                        {
                            byte[] xcBytes = new byte[SIZEBUFFER];
                            int bytes;
                            bytes = ss2.Receive(xcBytes, xcBytes.Length, 0);
                            str += Encoding.ASCII.GetString(xcBytes, 0, bytes);
                            ss2.Close();
                        }
                        if (str == "xc")
                        {
                            file.Seek(lStartPos, SeekOrigin.Current); //移动文件流中的当前指针
                        }
                        if (str == "bxc")
                        {
                            file.Close();
                            File.Delete(path);
                            file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); //写入文件流
                        }
                        if (str == "qx")
                        {
                            file.Close();
                            ss1.Shutdown(SocketShutdown.Both);
                            ss1.Close();

                        }
                        else
                        {

                            byte[] nbytes = new byte[SIZEBUFFER];
                            int nReadSize = 0;

                            nReadSize = ss1.Receive(nbytes, 0, nbytes.Length, SocketFlags.None);

                            ss1.Send(Encoding.ASCII.GetBytes(nReadSize.ToString()), Encoding.ASCII.GetBytes(nReadSize.ToString()).Length, 0); //返回接收到的数据
                            int TotleSize = nReadSize;

                            while (nReadSize > 0)
                            {
                                file.Write(nbytes, 0, nReadSize);

                                nReadSize = ss1.Receive(nbytes, 0, nbytes.Length, SocketFlags.None);

                                if (Encoding.UTF8.GetString(nbytes, 0, nReadSize) == "end")
                                {
                                    break;
                                }
                                ss1.Send(Encoding.ASCII.GetBytes(nReadSize.ToString()), Encoding.ASCII.GetBytes(nReadSize.ToString()).Length, 0); //返回接收到的数据
                                Console.WriteLine("接收   " + nReadSize + " 字节");

                                TotleSize += nReadSize;
                                Console.WriteLine("接受总数为" + TotleSize);
                            }

                            file.Close();

                            string sendStr = "Ok!Sucess!";
                            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                            ss1.Send(bs, bs.Length, 0);
                            ss1.Shutdown(SocketShutdown.Both);

                            ss1.Close();

                        }

                    }
                }

            }
            catch (SocketException e)
            {
                Console.WriteLine("{0}", e);
            }
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值