C# 超大文件发送与接收

发送端部分代码:

        public void startSendFileThread() {            
            try
            {               
                Thread sendFileThread = new Thread(new ThreadStart(sendFile));
                sendFileThread.Start();
            }
            catch {
                MessageBox.Show("线程开启或线程发送过中遇到问题失败。。。。。。");
                this.sendFlag = false;
            }
            finally
            {              
            }
        }       

        public void sendFile()
        {

            public Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(userIP),userPort);
            try
            {
                //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
                socketClient.SendBufferSize = 1024 * 1024*10;
                socketClient.ReceiveBufferSize = 1024 * 1024*10;
                socketClient.Connect(ipep);
               // MessageBox.Show("connected!!");
            }
            catch (SocketException e)
            {
                Console.WriteLine("unable to connect to server");
                Console.WriteLine(e.ToString());
            }
             FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            int partSize = 1024 * 100;
            long fileLength = fs.Length;
            long offset = 0;
            while (true)
            {
                if (offset + partSize >=fileLength)
                            partSize = Convert.ToInt32(fileLength - offset);
                byte[] temp = new byte[partSize];
                fs.Position = offset;
                fs.Read(temp, 0, partSize);
                socketClient.Send(temp, temp.Length, SocketFlags.None);//将数据发送到指定的终结点
               // myControl.TraFransfersSize += partSize;
                if (offset + partSize >= fileLength)
                    break;
                offset += partSize;                
            }
            //myChat.Rich_Out.AppendText("发送完成: " + fileName + "\n");  
            socketClient.Shutdown( SocketShutdown.Both);
            socketClient.Close();
           // myChat.RemoveFileInfoFromControl(fileName);
        }


接收端部分代码:

        public void Listener()   //监听 本地端口 5421
       {
           if (classTCPSocket == null)
               classTCPSocket = new ClassTCPSocket(5421);
           else
           {
               try
               {
                   thdUdp = new Thread(new ThreadStart(GetUDPData));   //创建一个线程
                   thdUdp.Start(); //执行当前线程
               }
               catch (Exception e)
               {
                   MessageBox.Show(e.ToString());  //显示线程的错误信息
               }
           }
       }
       public void GetUDPData()   //获取当前接收的消息
       {
            serverSocket = classTCPSocket.getTCPSocker().Accept();//等到一个TCPSocker
           byte[] Data =null;
           int number = 0;
           bool flag = true;
           while (flag)
           {               
                  Data = new byte[1024 * 10];
                  if ((number = serverSocket.Receive(Data)) != 0)
                  {
                      FileStream fs = null;
                      try
                      {
                          fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite);// File.OpenWrite(filePath);                        
                          fs.Seek(0, SeekOrigin.End);//将该流的当前位值设为0
                          fs.Write(Data, 0, number);//向文件中写入当前接收的信息
                       //   myControl.TraFransfersSize += number;            
                      }
                      finally
                      {
                          fs.Close();
                      }
                      
                  }
                  else flag=false;   
              }
          // myChat.Rich_Out.AppendText("接收成功: " + fileName + "\n文件大小:"+GetText(myControl.TraFransfersSize)+"\n");
           DoCleanOperation();
                     
       }

  public void DoCleanOperation(){
            if (serverSocket.Connected)
            {
                serverSocket.Shutdown(SocketShutdown.Both);
                serverSocket.Close();
            }
            classTCPSocket.Active = false;
           // myChat.RemoveFileInfoFromControl(fileName);// panelSendFile.Controls.Remove(myControl);
            thdUdp.Abort();
        
        }


//ClassTCPSocket

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Threading;

namespace QQClient
{
    public  class ClassTCPSocket
    {
        Socket tcpSocket = null;
        
        private int localPort = 5421;
        public int LocalPort
        {
            get { return localPort; }
            set { localPort = value; }
        }

        public ClassTCPSocket(int localPort) {
            this.localPort = localPort;
            init();
        }
       
        private string localHost = "127.0.0.1";
         public string LocalHost
        {
            get { return localHost; }
            set { localHost = value; }
        }

        private bool active = false;
         public bool Active
        {
            get { return active; }  
            set //该属性读取值
            {
                active = value;
                if (tcpSocket == null)
                    init();
                if (active)
                {

                    openListen();
                }
                else
                    stopListen();
            }
        }
        public void init(){
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ClassGetLocalInfo.getLocalhostIP()), localPort);//定义一网络端点,将本地IP地址和端口号以网络端点存储
            tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//定义一个Socket
            tcpSocket.Bind(ipep);//Socket与本地的一个终结点相关联       
        }

         public void openListen() {
             if (this.tcpSocket != null)
             {
                 tcpSocket.Listen(10);
                 //MessageBox.Show(tcpSocket.AddressFamily+":"+tcpSocket.LocalEndPoint);
             }
             else
             {
                 init();
                 tcpSocket.Listen(10);
             }
         }
         public void stopSocket() {
             if (this.tcpSocket != null)
             {
                 tcpSocket.Shutdown(SocketShutdown.Both);
                 tcpSocket.Close();
             }
         }
         public void stopListen() {
            if (this.tcpSocket != null && this.tcpSocket.Connected)
             {
                 tcpSocket.Shutdown(SocketShutdown.Both);
             }
         }
        public Socket getTCPSocker(){            
            return tcpSocket;
        }     
              
    }
}



       



posted @ 2011-12-04 10:11  love25444  阅读(43)  评论(0)    收藏  举报