基本信息
源码名称:tcp发送文件、接收文件 示例源码
源码大小:0.25M
文件格式:.rar
开发语言:C#
更新时间:2019-04-20
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍
可以实现tcp协议下的文件发送与接收





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

namespace Sender
{
	/// <summary>
	/// Form1 的摘要说明。
	/// </summary>
	public class Sender : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox txtTargetHostname;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox txtPort;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox txtFile;
		private System.Windows.Forms.Button btnBrowse;
		private System.Windows.Forms.Button btnStart;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label lblStatus;
		private System.Windows.Forms.Button btnCancel;
		private System.Windows.Forms.OpenFileDialog dlgOpenFile;
		/// <summary>
		/// 必需的设计器变量。
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Sender()
		{
			//
			// Windows 窗体设计器支持所必需的
			//
			InitializeComponent();
			//
			setStatusDelegate = new SetStatusDelegate(SetStatus);
		}

		/// <summary>
		/// 清理所有正在使用的资源。
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows 窗体设计器生成的代码
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{
			this.label1 = new System.Windows.Forms.Label();
			this.txtTargetHostname = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.txtPort = new System.Windows.Forms.TextBox();
			this.label3 = new System.Windows.Forms.Label();
			this.txtFile = new System.Windows.Forms.TextBox();
			this.btnBrowse = new System.Windows.Forms.Button();
			this.btnStart = new System.Windows.Forms.Button();
			this.label4 = new System.Windows.Forms.Label();
			this.lblStatus = new System.Windows.Forms.Label();
			this.btnCancel = new System.Windows.Forms.Button();
			this.dlgOpenFile = new System.Windows.Forms.OpenFileDialog();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(16, 16);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(100, 24);
			this.label1.TabIndex = 0;
			this.label1.Text = "目标IP/域名:";
			this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// txtTargetHostname
			// 
			this.txtTargetHostname.Location = new System.Drawing.Point(96, 16);
			this.txtTargetHostname.Name = "txtTargetHostname";
			this.txtTargetHostname.Size = new System.Drawing.Size(120, 21);
			this.txtTargetHostname.TabIndex = 1;
			this.txtTargetHostname.Text = "localhost";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(224, 16);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(40, 24);
			this.label2.TabIndex = 2;
			this.label2.Text = "端口:";
			this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// txtPort
			// 
			this.txtPort.Location = new System.Drawing.Point(264, 16);
			this.txtPort.Name = "txtPort";
			this.txtPort.Size = new System.Drawing.Size(48, 21);
			this.txtPort.TabIndex = 3;
			this.txtPort.Text = "8080";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(16, 48);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(168, 16);
			this.label3.TabIndex = 0;
			this.label3.Text = "要发送的文件:";
			this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// txtFile
			// 
			this.txtFile.Location = new System.Drawing.Point(16, 64);
			this.txtFile.Name = "txtFile";
			this.txtFile.Size = new System.Drawing.Size(232, 21);
			this.txtFile.TabIndex = 4;
			this.txtFile.Text = "";
			this.txtFile.TextChanged  = new System.EventHandler(this.txtFile_TextChanged);
			// 
			// btnBrowse
			// 
			this.btnBrowse.Location = new System.Drawing.Point(248, 64);
			this.btnBrowse.Name = "btnBrowse";
			this.btnBrowse.Size = new System.Drawing.Size(64, 21);
			this.btnBrowse.TabIndex = 5;
			this.btnBrowse.Text = "浏览...";
			this.btnBrowse.Click  = new System.EventHandler(this.btnBrowse_Click);
			// 
			// btnStart
			// 
			this.btnStart.Enabled = false;
			this.btnStart.Location = new System.Drawing.Point(16, 96);
			this.btnStart.Name = "btnStart";
			this.btnStart.Size = new System.Drawing.Size(80, 24);
			this.btnStart.TabIndex = 6;
			this.btnStart.Text = "开始";
			this.btnStart.Click  = new System.EventHandler(this.btnStart_Click);
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(16, 128);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(56, 16);
			this.label4.TabIndex = 7;
			this.label4.Text = "状态:";
			// 
			// lblStatus
			// 
			this.lblStatus.Location = new System.Drawing.Point(48, 128);
			this.lblStatus.Name = "lblStatus";
			this.lblStatus.Size = new System.Drawing.Size(272, 32);
			this.lblStatus.TabIndex = 8;
			this.lblStatus.Text = "就绪";
			// 
			// btnCancel
			// 
			this.btnCancel.Enabled = false;
			this.btnCancel.Location = new System.Drawing.Point(104, 96);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Size = new System.Drawing.Size(80, 24);
			this.btnCancel.TabIndex = 9;
			this.btnCancel.Text = "取消";
			this.btnCancel.Click  = new System.EventHandler(this.btnCancel_Click);
			// 
			// dlgOpenFile
			// 
			this.dlgOpenFile.Filter = "所有文件|*.*";
			this.dlgOpenFile.Title = "选择要发送的文件";
			// 
			// Sender
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
			this.ClientSize = new System.Drawing.Size(328, 173);
			this.Controls.Add(this.btnCancel);
			this.Controls.Add(this.lblStatus);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.btnStart);
			this.Controls.Add(this.btnBrowse);
			this.Controls.Add(this.txtFile);
			this.Controls.Add(this.txtPort);
			this.Controls.Add(this.txtTargetHostname);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label3);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "Sender";
			this.Text = "发送方";
			this.ResumeLayout(false);

		}
		#endregion

		#region 程序逻辑
		private Thread worker;
		private string hostname;
		private int port;
		private string filename;

		private void Start()
		{
			try // 捕获线程中止异常
			{
				SetStatus("连接中");
				TcpClient tcpClient = new TcpClient();
				tcpClient.SendTimeout = 30000;
				tcpClient.NoDelay = true;

				try // 捕获连接建立时出现的错误
				{
					tcpClient.Connect(hostname, port);
				}
				catch (Exception e)
				{
					SetStatus("连接出错:"   e.Message);
					InvokeCancel();
					worker = null;
					return;
				}
				BinaryWriter writer = new BinaryWriter(tcpClient.GetStream());

				try // 捕获文件传输中途出现的错误,并确保关闭连接
				{
					SetStatus("发送文件信息中");
					FileInfo fi = new FileInfo(filename);
					writer.Write(fi.Name);
					writer.Write(fi.Length);

					SetStatus("发送文件内容中");
					FileStream fs = fi.OpenRead();
					try // 保证关闭文件
					{
						long total = fi.Length;
						byte[] buffer = new byte[8192];
						int len;
						while ((len = fs.Read(buffer, 0, 8192)) != 0)
						{
							writer.Write(buffer, 0, len);
							SetStatus("发送文件内容中 - 剩余 "  
								(total -= len).ToString()   " 字节");
						}
						SetStatus("文件发送完毕");
						InvokeCancel();
					}
					finally
					{
						fs.Close();
					}
				}
				catch (Exception e)
				{
					SetStatus("文件传输中途出错:"   e.Message);
					InvokeCancel();
				}
				finally
				{
					try { writer.Close(); }
					catch {}
					try { tcpClient.Close(); }
					catch {}
				}
			}
			catch (ThreadAbortException)
			{
				SetStatus("用户中断");
				InvokeCancel();
			}
			finally
			{
				worker = null;
			}
		}
		#endregion

		#region 入口 & UI相关代码
		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Sender());
		}

		private void txtFile_TextChanged(object sender, System.EventArgs e)
		{
			btnStart.Enabled = (txtFile.Text.Length != 0);
		}

		private void btnBrowse_Click(object sender, System.EventArgs e)
		{
			if (dlgOpenFile.ShowDialog(this) == DialogResult.OK)
				txtFile.Text = dlgOpenFile.FileName;
		}

		private void btnStart_Click(object sender, System.EventArgs e)
		{
			hostname = txtTargetHostname.Text.Trim();
			if (hostname.Length == 0)
			{
				MessageBox.Show("请输入目标IP/域名。");
				txtTargetHostname.Focus();
				return;
			}
			port = 0;
			try
			{
				port = int.Parse(txtPort.Text);
				if (port < 1 || port > 65535) throw new ArgumentOutOfRangeException();
			}
			catch
			{
				MessageBox.Show("请输入有效的端口号。");
				txtPort.Focus();
				txtPort.SelectAll();
				return;
			}
			filename = txtFile.Text;
			if (!File.Exists(filename))
			{
				MessageBox.Show("请输入存在的文件名。");
				txtFile.Focus();
				txtFile.SelectAll();
				return;
			}
			btnStart.Enabled = false;
			btnCancel.Enabled = true;
			worker = new Thread(new ThreadStart(Start));
			worker.IsBackground = true;
			worker.Start();
		}

		private void btnCancel_Click(object sender, System.EventArgs e)
		{
			try { worker.Abort(); }
			catch {}
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			if (btnCancel.Enabled)
				e.Cancel = true;
			base.OnClosing(e);
		}
		#endregion

		#region 线程安全UI操作代码
		private delegate void SetStatusDelegate(string status);
		private SetStatusDelegate setStatusDelegate; // 赋值在构造函数里

		private void SetStatus(string status)
		{
			if (InvokeRequired)
				Invoke(setStatusDelegate, new object[] { status });
			else
				lblStatus.Text = status;
		}

		private void InvokeCancel()
		{
			if (InvokeRequired)
				Invoke(new MethodInvoker(InvokeCancel));
			else
			{
				btnCancel.Enabled = false;
				btnStart.Enabled = true;
			}
		}
		#endregion
	}
}