如何經過Socket TCP發送並接收一個文件?

一.小結數組

1.大包發小包收,只發一次。socket

2.發時把文件擴展名,文件長度也隨同一塊兒發送,方便接收端接收時另存爲正確的文件類型,並判斷是否已經接收完畢。ui

   若是不一塊兒發送,分爲文件擴展名,文件長度,文件內容,發送三次,在接收端,也可能會一塊兒收到,反而不利於解析。this

 

二.客戶發送端代碼spa

 

        private void btnSend_Click(object sender, EventArgs e)
        {
            //組合出遠程終結點  
            IPAddress ipAddress = IPAddress.Parse(this.txtIP3.Text);
            IPEndPoint hostEP = new IPEndPoint(ipAddress, Convert.ToInt32(this.txtPort3.Text));
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Connect(hostEP);

                //1.發送用戶協議
                string path1 = Environment.CurrentDirectory; //獲取應用程序的當前工做目錄。
                string doc = "YourSendFile.pdf";
 string path = Path.Combine(path1, doc);
                FileStream fs = File.Open(path, FileMode.Open);

                //文件內容
                byte[] bdata = new byte[fs.Length];
                fs.Read(bdata, 0, bdata.Length);
                fs.Close();
                
                //文件擴展名,固定3字節
                byte[] fileExtArray = Encoding.UTF8.GetBytes(string.Format("{0:D3}", currentDocExt));

                //文件長度, 固定爲20字節,前面會自動補零
                byte[] fileLengthArray = Encoding.UTF8.GetBytes(bdata.Length.ToString("D20"));
                
                //合併byte數組
                byte[] fileArray = CombomBinaryArray(fileExtArray, fileLengthArray);

                //合併byte數組
                byte[] bdata1 = CombomBinaryArray(fileArray, bdata);

                //發文件長度+文件內容
                socket.Send(bdata1, bdata1.Length, 0);

                //2.接收
                //聲明接收返回內容的字符串  
                string recvStr = "";

                //聲明字節數組,一次接收數據的長度爲 1024 字節  
                byte[] recvBytes = new byte[1024];

                //返回實際接收內容的字節數  
                int bytes = 0;

                //循環讀取,直到接收完全部數據  
                while (true)
                {
                    bytes = socket.Receive(recvBytes, recvBytes.Length, 0);
                    //讀取完成後退出循環  
                    if (bytes <= 0) break;

                    //將讀取的字節數轉換爲字符串  
                    recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
                }              


                //禁用 Socket  
                socket.Shutdown(SocketShutdown.Both);

                //關閉 Socket  
                socket.Close();

                //... do some busness logic ...

            }
            catch (Exception e1)
            {
                throw e1;
            }
        }

 

三.服務接收端代碼code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Xml;
using System.Configuration;
using System.Windows.Forms;
using System.IO;

namespace ConsoleAppServer
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            
            bool Done = false;
            IPAddress ipAddress = IPAddress.Parse(ConfigurationSettings.AppSettings["IP"].ToString());
            IPEndPoint hostEP = new IPEndPoint(ipAddress, Convert.ToInt32(ConfigurationSettings.AppSettings["Port"]));
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(hostEP);
            socket.Listen(3);
            while (!Done)
            {
                Console.WriteLine("waiting for client");

                Socket client = socket.Accept();

                Console.WriteLine("connected client");

                //1.接收
                //聲明字節數組,一次接收數據的長度爲 1024 字節  
                byte[] recvBytes = new byte[1024];
                //返回實際接收內容的字節數  
                int bytes = 0;
                                
                int FileLength = 0; // 900866;
                int ReceivedLength = 0;

                //1.0 接收文件擴展名
                bytes = client.Receive(recvBytes, 3, 0);
                string fileExt = Encoding.UTF8.GetString(recvBytes, 0, bytes);

                string vFilePath = Environment.CurrentDirectory;
                string vFileName = vFilePath + "\\Tmp" + Guid.NewGuid().ToString() + "." + fileExt;

                //建立文件流,而後讓文件流來根據路徑建立一個文件
                FileStream fs = new FileStream(vFileName, FileMode.Create);

                //1.1 接收文件長度
                bytes = client.Receive(recvBytes, 20, 0);
                //將讀取的字節數轉換爲字符串  
                string fileLength = Encoding.UTF8.GetString(recvBytes, 0, bytes);
                FileLength = Convert.ToInt32(fileLength);

                //1.2接收文件內容
                while (ReceivedLength < FileLength)
                {
                    bytes = client.Receive(recvBytes, recvBytes.Length, 0);
                    ReceivedLength += bytes;
                    fs.Write(recvBytes, 0, bytes);
                }

                fs.Flush();
                fs.Close();


                //... do some business logic ...   
               string returnData = SomeBusinessLogic();

                //2.發送
                byte[] bdata = Encoding.UTF8.GetBytes(returnData);
                client.Send(bdata, bdata.Length, 0);

                client.Close();
            }

            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }
        
    }
}
相關文章
相關標籤/搜索