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("接收成功");
                }
            }
        }
      
    }
}

  实例图

 

posted @ 2017-02-27 23:02  空白凌乱感  阅读(14266)  评论(0编辑  收藏  举报