使用TCP协议传输文件 C# (Demo全部代码)

关于TCP文件传输

在内网中,通过编写WPF程序传输文件,建立server和client端,实现文件发送和接收。程序代码和功能比较简单,目的主要是为了实现逻辑。话不多说,直接贴上代码。

Server端代码

UI部分,XAML代码:


    
        
        

后端部分

using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TCPService
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void load()
        {
            TcpListener tl = null;
            Socket socket = null;
            FileStream fs = null;
            BinaryWriter writer = null;
            while (true)
            {
                try
                {
                    tl = new TcpListener(IPAddress.Any, int.Parse(Port));
                    tl.Start();
                    socket = tl.AcceptSocket();
                    string path = digOpen();
                    if (path == null) continue;
                    fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    writer = new BinaryWriter(fs);
                    int count;
                    byte[] b = new byte[4098];
                    while ((count = socket.Receive(b, b.Length, SocketFlags.None)) != 0) writer.Write(b, 0, count);
                    UISetMessage("保存文件成功!  文件保存到 ---> " + path);
                }
                catch (Exception ex)
                {
                    UISetMessage(ex.ToString());
                }
                finally
                {
                    if (tl != null) tl.Stop();
                    if (socket != null) socket.Close();
                    if (fs != null) fs.Close();
                    if (writer != null) writer.Close();
                }
            }
        }
        string IP;
        string Port;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            IP = IpText.Text;
            Port = PortText.Text;
        }

        delegate object UIGet();
        private string digOpen()
        {
            object path = Dispatcher.Invoke(new UIGet(() => {
                CommonOpenFileDialog dialog = new CommonOpenFileDialog();
                dialog.Title = "检测到文件请求,请选择目录";
                dialog.IsFolderPicker = true;//True选择文件目录,false选择文件夹
                if (Convert.ToBoolean(dialog.ShowDialog()))
                {
                    return dialog.FileName;
                }
                return null;
            }));
            return path == null ? null : path + @"\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip";
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }
        bool isStart = false;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (isStart) return;
            Thread t = new Thread(load);
            t.Start();
            UISetMessage("等待文件传输...");
            isStart = true;
        }
        public void UISetMessage(string data)
        {
            Dispatcher.Invoke(new Action(() => {
                message.AppendText("\r\n" + data);
            }));
        }
    }
}

Client端代码

UI部分,XAML代码:


    
        

后端部分

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TCPClient
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        string path;
        bool isEnd = true;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "请选择发送的文件";
            if (Convert.ToBoolean(dlg.ShowDialog()) && isEnd)
            {
                path = dlg.FileName;
                Thread t = new Thread(send);
                t.Start();
                isEnd = false;
            }
        }
        private void send()
        {
            TcpClient tcpClient = null;
            FileStream fs = null;
            BinaryReader reader = null;
            try
            {
                UISetMessage("正在发送...");
                tcpClient = new TcpClient();
                tcpClient.Connect(IPAddress.Parse(UIGetIpText()), int.Parse(UIGetPortText()));
                fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
                reader = new BinaryReader(fs);
                byte[] b = new byte[fs.Length];
                int index;
                while ((index = reader.Read(b, 0, b.Length)) != 0)
                {
                    tcpClient.Client.Send(b, index, SocketFlags.None);
                }
                tcpClient.Client.Shutdown(SocketShutdown.Both);
                UISetMessage("发送成功!");
            }
            catch (Exception ex)
            {
                UISetMessage(ex.ToString());
            }
            finally
            {
                if (tcpClient != null) tcpClient.Close();
                if (fs != null) fs.Close();
                if (reader != null) reader.Close();
                isEnd = true;
            }
        }
        delegate object UIGet();
        public string UIGetIpText()
        {
            return Dispatcher.Invoke(new UIGet(() => { return IpText.Text; })).ToString();
        }
        public string UIGetPortText()
        {
            return Dispatcher.Invoke(new UIGet(() => { return PortText.Text; })).ToString();
        }
        public void UISetMessage(string data)
        {
            Dispatcher.Invoke(new Action(() => {
                message.AppendText("\r\n" + data);
            }));
        }
    }
}

你可能感兴趣的:(网络基础,网络通信,wpf,tcpip)