TCP方式下用NetWorkStream来进行文件的传输

先看图:

代码:

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

namespace tcpFileTrans
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 存储目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if(fbd.ShowDialog()==DialogResult.OK)
            {
                textBox1.Text = fbd.SelectedPath;
            }
        }
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog()==DialogResult.OK)
            {
                textBox3.Text=ofd.FileName;
            }
        }
        /// <summary>
        /// 启动服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        TcpListener listener;
        delegate void SetTextCallBack(string text);
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() == "" || textBox3.Text.Trim() == "")
            {
                MessageBox.Show("请先选择目录和文件!");
            }
            else
            {
                button1.Enabled = false;
                this.Text = "服务端已启动";
                listener = new TcpListener(IPAddress.Any, 3000);
                listener.Start();
                Thread th = new Thread(new ThreadStart(ReceiveMsg));
                th.Start();
                th.IsBackground = true;
            }
           
           
            
        }
        public void ReceiveMsg()
        {

            try
            {
                
                int size = 0;
                int len = 0;
                string path = Path.Combine(textBox1.Text, Path.GetFileName(textBox3.Text));
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                TcpClient client = listener.AcceptTcpClient();
                NetworkStream stream = client.GetStream();
                byte[] buffer = new byte[client.ReceiveBufferSize];
                while ((size = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fs.Write(buffer, 0, size);
                    len += size;
                }
                fs.Flush();
                stream.Flush();
                stream.Close();
                client.Close();
            }
            catch { }   

        }
        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (button1.Enabled == false)
            {
                if (textBox1.Text.Trim() == "" || textBox3.Text.Trim() == "")
                {
                    MessageBox.Show("目录或文件不能为空!");
                }
                else
                {
                    TcpClient client = new TcpClient();
                    string ip = textBox2.Text;
                    client.Connect(IPAddress.Parse(ip), 3000);
                    NetworkStream ns = client.GetStream();
                    FileStream fs = new FileStream(textBox3.Text, FileMode.Open);
                    int size = 0;//初始化读取的流量为0
                    long len = 0;//初始化已经读取的流量
                    while (len < fs.Length)
                    {
                        byte[] buffer = new byte[200 * 1024];
                        size = fs.Read(buffer, 0, buffer.Length);
                        ns.Write(buffer, 0, size);
                        len += size;
                        //Pro((long)len);
                    }
                    MessageBox.Show("文件发送成功!");
                    fs.Flush();
                    ns.Flush();
                    fs.Close();
                    ns.Close();
                }
            }
            else
            {
                MessageBox.Show("请先启动服务器!");
            }     
            
        }
    }
}


实现原理很简单:

客户端:先连接TCP,将文件用文件流的方式读入缓冲区,然后将缓冲区的数据写入网络流中存储。

服务端:接受连接请求,从网络流中读取数据,再写入指定的文件流。

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值