我想用.net做文件传输。像qq传输文件一样。谁知道帮帮我 啊。我是做毕业设计的。
參考答案:用socket编程的话,可以参考下面:
共两个窗体,
第一个窗体,设置端口,里面有个方法:
private void buttonConfirm_Click(object sender, System.EventArgs e)
{
if(textPort.Text.Length == 0)
{
string strText = "请输入端口号";
string strCaption = "错误";
MessageBox.Show(strText,strCaption);
}
else
{
try
{
MainForm.port = System.Convert.ToInt32(textPort .Text,10);
MainForm.tcpl = new TcpListener(MainForm.port);
}
catch
{
string strText = "请输入正确的端口号";
string strCaption = "错误";
MessageBox.Show(strText,strCaption);
return;
}
this.Close();
}
}
另一个是发送文件的窗体:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.IO;
namespace CSFile
{
/// <summary>
/// Summary description for MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Button buttonConnect;
private System.Windows.Forms.Button buttonDisconnect;
private System.Windows.Forms.Button buttonSendFile;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label labelIP;
private System.Windows.Forms.Label labelPort;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem menuFile;
private System.Windows.Forms.MenuItem menuF_exi;
private System.Windows.Forms.MenuItem menuHelp;
private System.Windows.Forms.MenuItem menuH_ref;
private System.Windows.Forms.MenuItem menuH_abo;
private System.Windows.Forms.RichTextBox richOutputBox;
private System.Windows.Forms.TextBox textIP;
private System.Windows.Forms.TextBox textPort;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private setPortForm portform;
private Thread waitThread;
private Thread recvThread;
private bool isConnecting = false;
private bool isConnected = false;
private bool isClient = false;
private TcpClient tcpc;
private TcpClient tcpc2;
static public TcpListener tcpl;
static public int port;
private NetworkStream nsc;
private NetworkStream nsl;
private FileStream fileReader;
private FileStream fileWriter;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private const string infDisconnect = "######DISCONNECT######";
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
private void MainForm_Load(object sender, System.EventArgs e)
{
portform = new setPortForm();
portform.ShowDialog();
tcpl.Start();
waitThread = new Thread(new ThreadStart(waitConnection));
waitThread.Start();
}
protected override void OnClosed(EventArgs e)
{
if(isConnecting)
{
if(isClient)
{
disconnect(tcpc,nsc);
}
else
{
disconnect(tcpc2,nsl);
}
}
tcpl.Stop();
waitThread.Abort();
if(isConnected)
{
recvThread.Abort();
}
base.OnClosed(e);
}
private void waitConnection()
{
tcpc2 = tcpl.AcceptTcpClient();
nsl = tcpc2.GetStream();
string strText = "用户请求连接,接受吗?";
string strCaption = "连接请求";
MessageBoxButtons msbbutton = MessageBoxButtons.YesNo;
MessageBoxIcon msbIcon = MessageBoxIcon.Question;
MessageBoxDefaultButton msbDbutton = MessageBoxDefaultButton.Button1;
DialogResult diaRes
= MessageBox.Show(strText,strCaption,msbbutton, msbIcon,msbDbutton);
string strResp;
byte[] byteResp;
if(diaRes == DialogResult.Yes)
{
strResp = "#";
byteResp = Encoding.ASCII.GetBytes(strResp.ToCharArray());
nsl.Write(byteResp, 0, byteResp.Length);
isConnecting = true;
isConnected = true;
isClient = false;
buttonConnect.Enabled = false;
buttonDisconnect.Enabled = true;
buttonSendFile.Enabled = true;
recvThread = new Thread(new ThreadStart(ReceiveFile));
recvThread.Start();
}
else if(diaRes == DialogResult.No)
{
strResp = "##";
byteResp = Encoding.ASCII.GetBytes(strResp.ToCharArray());
nsl.Write(byteResp, 0, byteResp.Length);
nsl.Close();
tcpc2.Close();
disconnect();
}
}
private void disconnect()
{
buttonConnect.Enabled = true;
buttonDisconnect.Enabled = false;
buttonSendFile.Enabled = false;
isConnecting = false;
waitThread = new Thread(new ThreadStart(waitConnection));
waitThread.Start();
}
private void disconnect(TcpClient tcpc,NetworkStream ns)
{
byte[] write = new byte[64];
write = Encoding.Unicode.GetBytes(infDisconnect.ToCharArray());
ns.Write(write, 0, write.Length);
ns.Close();
tcpc.Close();
disconnect();
}
private void ReceiveFile()
{
// 如果是客户端
if(isClient)
{
// 调用客户端接收文件的实现函数
ReceiveFile(tcpc,nsc);
}
// 如果是服务端
else
{
// 调用服务端接收文件的实现函数
ReceiveFile(tcpc2,nsl);
}
}
private void ReceiveFile(TcpClient tcpc,NetworkStream ns)
{
// 读取信息的缓冲区
byte[] read = new byte[1024];
// 获取流
ns = tcpc.GetStream();
// 读取数据到缓冲区中
ns.Read(read, 0, read.Length);
// 把数据转换成字符串
string strout = Encoding.Unicode.GetString(read);
// 如果是断开连接信号
if(string.Compare(strout,infDisconnect) == 0)
{
// 显示连接断开信息
string strdcnt = "The connection has been disconnected.\n";
richOutputBox.AppendText(strdcnt);
richOutputBox.Focus();
// 关闭流
ns.Close();
// 关闭连接
tcpc.Close();
// 断开连接处理工作
disconnect();
}
// 如果传来的是文件名信息
else
{
// 提示接收文件的信息
string strText = "对方准备传送文件" + strout;
string strCaption = "提示";
MessageBox.Show(strText,strCaption);
// 打开保存文件的对话框
saveFileDialog = new SaveFileDialog();
// 设置默认保存的文件名
saveFileDialog.FileName = strout;
saveFileDialog.ShowDialog();
// 当前时间信息
DateTime now = DateTime.Now;
string strDateLine =
now.ToShortDateString() + " " + now.ToLongTimeString();
// 在文件信息窗口显示提示信息
richOutputBox.AppendText(strDateLine);
richOutputBox.AppendText("\n");
richOutputBox.AppendText("正在接收文件...\n");
// 获取保存文件对话框中选定的文件路径
string path = saveFileDialog.FileName;
// 创建基于该文件的流
fileWriter = new FileStream(path,FileMode.Create);
// 读取网络流数据,写入文件流数据的缓冲区
byte[] write = new byte[1];
// 从网络流中读取数据到缓冲区
int bytes = ns.Read(write,0,write.Length);
// 计算文件大小的变量
ulong count = 0;
// 当数据未读取完,循环读取
while(bytes != 0)
{
// 将数据写入文件
fileWriter.Write(write,0,write.Length);
// 继续读取
bytes = ns.Read(write,0,write.Length);
// 文件长度计数
count ++;
}
// 关闭FileStream
fileWriter.Close();
// 关闭NetworkStream
ns.Close();
// 关闭连接
tcpc.Close();
// 断开连接的处理工作
disconnect();
// 用字符串表示文件大小
string filelength = System.Convert.ToString(count);
// 提示完成信息和文件大小的信息
richOutputBox.AppendText("接收完毕\n");
richOutputBox.AppendText("文件大小:" +filelength +"字节");
// 分隔不同的信息
richOutputBox.AppendText("\n\n");
}
}
private void SendFile(TcpClient tcpc,NetworkStream ns)
{
// 存放文件名的变量
string fileName = fileReader.Name;
// 存放文件大小的变量
string fileSize = fileReader.Length.ToString();
// 组织显示信息头
DateTime now = DateTime.Now;
string strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
string strBeginLine =strDateLine + "\t发送:\n";
// 在本方文件信息框上显示发送文件的日期时间
richOutputBox.AppendText(strDateLine);
// 显示文件名
richOutputBox.AppendText(fileName);
richOutputBox.AppendText("\n");
// 显示文件大小
richOutputBox.AppendText(fileSize + "字节");
richOutputBox.AppendText("\n\n");
// 显示焦点处信息
richOutputBox.Focus();
// 读取文件流数据的辅助变量
int bytes;
byte[] read = new byte[1];
// 循环读出文件数据并写入网络流
while(true)
{
// 读文件数据到缓冲区中
bytes = fileReader.Read(read,0,read.Length);
// 如果读完,退出循环
if(bytes == 0)
{
break;
}
// 把缓冲区的数据写入网络流
ns.Write(read,0,read.Length);
}
// 关闭FileStream
fileReader.Close();
// 关闭NetworkStream
ns.Close();
// 关闭连接
tcpc.Close();
// 断开连接的处理工作
disconnect();
}
private void buttonConnect_Click(object sender, System.EventArgs e)
{
if(textIP.Text.Length == 0 || textPort.Text.Length == 0)
{
string strText = "请输入完整的IP地址和端口信息";
string strCaption = "错误";
MessageBoxButtons msbbutton = MessageBoxButtons.AbortRetryIgnore;
MessageBoxIcon msbIcon = MessageBoxIcon.Error;
MessageBox.Show(strText,strCaption,msbbutton,msbIcon);
return;
}
tcpc = new TcpClient();
string IP = textIP.Text;
int portnum = System.Convert.ToInt32(textPort.Text,10);
try
{
tcpc.Connect(IP,portnum);
}
catch(ArgumentOutOfRangeException)
{
string strText = "请输入有效的端口号";
string strCaption = "错误";
MessageBox.Show(strText,strCaption);
return;
}
catch(SocketException)
{
string strText = "找不到对方,请重新确认对方的网络参数";
string strCaption = "错误";
MessageBox.Show(strText,strCaption);
return;
}
nsc = tcpc.GetStream();
byte[] read = new byte[2];
int bytes = nsc.Read(read, 0, read.Length);
if(bytes == 1)
{
string strText = "已建立连接";
string strCaption = "完成";
MessageBox.Show(strText,strCaption);
isConnecting = true;
isConnected = true;
isClient = true;
buttonConnect.Enabled = false;
buttonDisconnect.Enabled = true;
buttonSendFile.Enabled = true;
recvThread = new Thread(new ThreadStart(ReceiveFile));
recvThread.Start();
}
else if(bytes == 2)
{
string strText = "对方拒绝连接请求";
string strCaption = "完成";
MessageBox.Show(strText,strCaption);
}
}
//
private void buttonDisconnect_Click(object sender, System.EventArgs e)
{
if(isClient)
{
disconnect(tcpc,nsc);
}
else
{
disconnect(tcpc2,nsl);
}
}
private void buttonSendFile_Click(object sender, System.EventArgs e)
{
// 创建一个选择打开文件对话框
openFileDialog = new OpenFileDialog();
// 获取点中按钮的类型
DialogResult diaRes = openFileDialog.ShowDialog();
// 如果按下了取消按钮则退出
if(diaRes == DialogResult.Cancel)
{
return;
}
// 获取选取的文件路径
string filePath = openFileDialog.FileName;
// 为该文件创建一个文件流
fileReader = new FileStream(filePath,FileMode.Open);
// ③
// 用自定义的getName函数取出不带路径的文件名
string fileName = getName(filePath);
// 发送数据的缓冲区
byte[] write = new byte[128];
// 将文件名编码为Unicode格式存储放到数组中
write = Encoding.Unicode.GetBytes(fileName.ToCharArray());
// 根据当前状态发送文件名和文件内容
// 如果是客户端
if(isClient)
{
// 将文件名写入流中
nsc.Write(write,0,write.Length);
// 调用发送文件的实现函数
SendFile(tcpc,nsc);
}
// 如果是服务端
else
{
// 将文件名写入流中
nsl.Write(write,0,write.Length);
// 调用发送文件的实现函数
SendFile(tcpc2,nsl);
}
}
private string getName(string filepath)
{
// 以完整文件路径长度减1作为下标
int index = filepath.Length - 1;
// 从后往前寻找文件路径串中的最后一个斜杆
while(filepath[index] != '\\')
{
index--;
}
// 将包括最后一个斜杆之前的串删去
return filepath.Remove(0,index+1);
}
private void menuF_exi_Click(object sender, System.EventArgs e)
{
this.Close();
}
}