实例介绍
【实例简介】可以实现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 } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论