王朝知道
分享
 
 
 

.net中怎么样实现文件传输。谁知道帮帮我啊。我的qq是***********

王朝知道·作者佚名  2009-07-29  
宽屏版  字体: |||超大  
 
分类: 电脑/网络 >> 程序设计 >> 其他编程语言
 
问题描述:

我想用.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();

}

}

小贴士:① 若网友所发内容与教科书相悖,请以教科书为准;② 若网友所发内容与科学常识、官方权威机构相悖,请以后者为准;③ 若网友所发内容不正确或者违背公序良俗,右下举报/纠错。
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
如何用java替换看不见的字符比如零宽空格&#8203;十六进制U+200B
 干货   2023-09-10
网页字号不能单数吗,网页字体大小为什么一般都是偶数
 干货   2023-09-06
java.lang.ArrayIndexOutOfBoundsException: 4096
 干货   2023-09-06
Noto Sans CJK SC字体下载地址
 干货   2023-08-30
window.navigator和navigator的区别是什么?
 干货   2023-08-23
js获取referer、useragent、浏览器语言
 干货   2023-08-23
oscache遇到404时会不会缓存?
 干货   2023-08-23
linux下用rm -rf *删除大量文件太慢怎么解决?
 干货   2023-08-08
刀郎新歌破世界纪录!
 娱乐   2023-08-01
js实现放大缩小页面
 干货   2023-07-31
生成式人工智能服务管理暂行办法
 百态   2023-07-31
英语学习:过去完成时The Past Perfect Tense举例说明
 干货   2023-07-31
Mysql常用sql命令语句整理
 干货   2023-07-30
科学家复活了46000年前的虫子
 探索   2023-07-29
英语学习:过去进行时The Past Continuous Tense举例说明
 干货   2023-07-28
meta name="applicable-device"告知页面适合哪种终端设备:PC端、移动端还是自适应
 干货   2023-07-28
只用css如何实现打字机特效?
 百态   2023-07-15
css怎么实现上下滚动
 干货   2023-06-28
canvas怎么画一个三角形?
 干货   2023-06-28
canvas怎么画一个椭圆形?
 干货   2023-06-28
canvas怎么画一个圆形?
 干货   2023-06-28
canvas怎么画一个正方形?
 干货   2023-06-28
中国河南省郑州市金水区蜘蛛爬虫ip大全
 干货   2023-06-22
javascript简易动态时间代码
 干货   2023-06-20
感谢员工的付出和激励的话怎么说?
 干货   2023-06-18
 
>>返回首页<<
 
 
 
静静地坐在废墟上,四周的荒凉一望无际,忽然觉得,凄凉也很美
© 2005- 王朝网络 版权所有