using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net.Sockets;
namespace FileSender
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
setStatusDelegate = new SetStatusDelegate(SetStatus);
}
#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("发送文件内容中");
getsavefilename FileStream fs = fi.OpenRead();
try // 保证关闭文件
{
double total = fi.Length/(1024*1024);
byte[] buffer = new byte[8192];
int len;
while ((len = fs.Read(buffer, 0, 8192)) != 0)
{
writer.Write(buffer, 0, len);
SetStatus("发送文件内容中 - 剩余 " + (total -= len/(1024*1024.0)).ToString() + "MB");
}
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
private void button3_Click(object sender, EventArgs e)
{
hostname = textBox1.Text.Trim();
if (hostname.Length == 0)
{
MessageBox.Show("请输入目标IP/域名。");
textBox1.Focus(); //光标焦点定位
return;
}
port = 0;
try
{
port = Int32.Parse(textBox2.Text);
if (port < 1 || port > 65535)
throw new ArgumentOutOfRangeException();
}
catch
{
MessageBox.Show("请输入有效的端口号。");
textBox2.Focus();
textBox2.SelectAll();
return;
}
//打开要发送的文件
OpenFileDialog Ofd = new OpenFileDialog();
Ofd.InitialDirectory = "C:/";
Ofd.Filter = "所有文件|*.*";
Ofd.FilterIndex = 1;
if (Ofd.ShowDialog(this) == DialogResult.OK)
filename = Ofd.FileName;
if (!File.Exists(filename))
{
MessageBox.Show("请输入存在的文件名。");
return;
}
button3.Enabled = false;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论