C# TcpClient網絡編程傳輸文件的示例

一、簡述

  利用C# TcpClient在局域網內傳輸文件,可是文件發送到對面的時候卻要重新命名文件的。那可不可以連著文件名與文件一起發過去呢?

二、內容

  如上圖,把文件名字符流的長度的值的字符流(這個文件名字符流長度的值固定是11位的字符串,不足11位前面補0)與文件名的字符流合為一個byte數組然後與文件發送到對面。對面接收後解析出文件名字符流長度的值後,再根據長度解析出文件名,接下來再獲取文件流。

  服務端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TCPSendFile
{
    public partial class Form1 : Form
    {
        public delegate void TxtReceiveAddContentEventHandler(string txtValue);
        
        public Form1()
        {
            InitializeComponent();
        }
       
        public void TxtAddContent(string txtValue)
        {
            if (textBox1.InvokeRequired)
            {
                TxtReceiveAddContentEventHandler addContent = TxtAddContent;
                textBox1.Invoke(addContent, new object[] { txtValue });
            }
            else
            {
                textBox1.Text = txtValue + "\r\n" + textBox1.Text;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            TcpListener tcpListener = new TcpListener(IPAddress.Any, 18001);
            tcpListener.Start();
            textBox1.Text = "開始偵聽...";
            Thread thread = new Thread(SendFileFunc);
            thread.Start(tcpListener);
            thread.IsBackground = true;
        }

        public void SendFileFunc(object obj)
        {
            TcpListener tcpListener = obj as TcpListener;
            while (true)
            {
                try
                {
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();
                    if (tcpClient.Connected)
                    {
                        NetworkStream stream = tcpClient.GetStream();
                        string fileName = "testfile.rar";

                        byte[] fileNameByte = Encoding.Unicode.GetBytes(fileName);

                        byte[] fileNameLengthForValueByte = Encoding.Unicode.GetBytes(fileNameByte.Length.ToString("D11"));
                        byte[] fileAttributeByte = new byte[fileNameByte.Length + fileNameLengthForValueByte.Length];
                       
                        fileNameLengthForValueByte.CopyTo(fileAttributeByte, 0);  //文件名字符流的長度的字符流排在前面。
                      
                        fileNameByte.CopyTo(fileAttributeByte, fileNameLengthForValueByte.Length);  //緊接著文件名的字符流
                     
                        stream.Write(fileAttributeByte, 0, fileAttributeByte.Length);
                        FileStream fileStrem = new FileStream(Application.StartupPath + "\\WebFile\\" + fileName, FileMode.Open);

                        int fileReadSize = 0;
                        long fileLength = 0;
                        while (fileLength < fileStrem.Length)
                        {
                            byte[] buffer = new byte[2048];
                            fileReadSize = fileStrem.Read(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, fileReadSize);
                            fileLength += fileReadSize;

                        }
                        fileStrem.Flush();
                        stream.Flush();
                        fileStrem.Close();
                        stream.Close();

                        TxtAddContent(string.Format("{0}文件發送成功", fileName));
                    }

                   
                }
                catch (Exception ex)
                {
                    
                }
            }
        }
    }
}

  客戶端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TCPReceiveFile
{
    public partial class Form1 : Form
    {
        public delegate void TxtReceiveAddContentEventHandler(string txtValue);
        public Form1()
        {
            InitializeComponent();
        }
        public void TxtReceiveAddContent(string txtValue)
        {
            if (txtReceive.InvokeRequired)
            {
                TxtReceiveAddContentEventHandler addContent = TxtReceiveAddContent;
                txtReceive.Invoke(addContent, new object[] { txtValue });
            }
            else
            {
                txtReceive.Text = txtValue + "\r\n" + txtReceive.Text;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 18001);
            TxtReceiveAddContent("連接中。。。。。");
            Thread th = new Thread(ReceiveFileFunc);
            th.Start(ipEndPoint);
            th.IsBackground = true;
        }

        private void ReceiveFileFunc(object obj)
        {
            IPEndPoint ipEndPoint = obj as IPEndPoint;
            TcpClient tcpClient = new TcpClient();
            try
            {
                tcpClient.Connect(ipEndPoint);
            }
            catch
            {
                TxtReceiveAddContent("連接失敗,找不到服務器!");
            }

            if (tcpClient.Connected)
            {
               
                NetworkStream stream = tcpClient.GetStream();
                if (stream != null)
                {

                    byte[] fileNameLengthForValueByte = Encoding.Unicode.GetBytes((256).ToString("D11"));
                    byte[] fileNameLengByte = new byte[1024];
                    int fileNameLengthSize = stream.Read(fileNameLengByte, 0, fileNameLengthForValueByte.Length);
                    string fileNameLength = Encoding.Unicode.GetString(fileNameLengByte, 0, fileNameLengthSize);
                    TxtReceiveAddContent("文件名字符流的長度為:" + fileNameLength);

                    int fileNameLengthNum = Convert.ToInt32(fileNameLength);
                    byte[] fileNameByte = new byte[fileNameLengthNum];

                    int fileNameSize = stream.Read(fileNameByte, 0, fileNameLengthNum);
                    string fileName = Encoding.Unicode.GetString(fileNameByte, 0, fileNameSize);
                    TxtReceiveAddContent("文件名為:" + fileName);

                    string dirPath = Application.StartupPath + "\\WebFile";
                    if(!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }
                    FileStream fileStream = new FileStream(dirPath + "\\" + fileName, FileMode.Create, FileAccess.Write);
                    int fileReadSize = 0;
                    byte[] buffer = new byte[2048];
                    while ((fileReadSize = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fileStream.Write(buffer, 0, fileReadSize);

                    }
                    fileStream.Flush();
                    fileStream.Close();
                    stream.Flush();
                    stream.Close();
                    tcpClient.Close();
                    TxtReceiveAddContent("接收成功");
                }
            }
        }
      
    }
}

  實例圖

以上就是C# TcpClient網絡編程傳輸文件的示例的詳細內容,更多關於C# TcpClient傳輸文件的資料請關註WalkonNet其它相關文章!

推薦閱讀:

    None Found