文件传输协议的简单设计与实现_第1页
文件传输协议的简单设计与实现_第2页
文件传输协议的简单设计与实现_第3页
文件传输协议的简单设计与实现_第4页
文件传输协议的简单设计与实现_第5页
已阅读5页,还剩35页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

课程设计课程名称计算机网络课程设计题目名称文件传输协议的简单设计与实现学生学院 专业班级____ 学号学生姓名_______________ 指导教师___________ 文件传送是各种计算机网络实现的基本功能,文件传送协议是一种最基本的应用层协议按照客户/服务器的模式进行工作,提供交互式的访问,是INTERNET使用最广泛的协议之一。文件传输协议的简单设计与实现建立在计1.1具体设计任务----------------------------------------------181.2基本思路及所涉及的相关理论--------------------------------181.2.1基本思路-------------------------------------------------182.2.2相关理论--------------------------------------------181.3设计流程图------------------------------------------------191.4实验运行情况----------------------------------------------191.5核心程序--------------------------------------------------222.5.1服务器(sever)程序---------------------------------222.5.2客户(client)程序----------------------------------291.6心得体会-----------------------------------------------------------------------------37参考文献--------------------------------------------------------382、文件传输协议的简单设计与实现2.2.2相关理论文件传送是各种计算机网络都实现的基本功能,文件传送协议是一种最基本的应用层协议按照客户/服务器的模式进行工作,提供交互式的访问,是socket接2.5核心程序2.5.1服务器(server)程序如下usingSystem。usingSystem.Collections.Generic。usingSystem.Linq。usingSystem.Text。usingSystem.Threading。usingSystem.Net。usingSystem.Net.Sockets。usingSystem.IO。usingSystem.Windows.FspaceTCP文件传输_服务器{classWorkThread{byte[]bufferSize=4096。Threadmythread。Sockethandler。publicWorkThread(SocketworkSocket){handler=workSocket。buffer=newbyte[bufferSize]。mythread=newThread(BeginCommunication)。}publicvoidStart(){mythread.Start()。}publicvoidAbort(){mythread.Abort()。}privatevoidBeginCommunication(){while(true)//从客户端接收数据,直到连接断开{try{intreCount=handler.Receive(buffer)。stringinsStr=Encoding.BigEndianUnicode.GetString(buffer,0,reCount)。if(insStr.Substring(0,4)=="name")//收到下文件请求{stringfileName=insStr.Substring(5,insStr.Length-5)。SendFile(fileName,handler)。}elseif(insStr.Substring(0,4)=="boot")//收到获取根目录请求{stringlistStr=GetFileNames("F:",false)。SendString(handler,listStr)。}elseif(insStr.Substring(0,4)=="path")//收到获取指定目录内容请求{stringpath=insStr.Substring(5,insStr.Length-5)。stringlistStr=GetFileNames(path,false)。SendString(handler,listStr)。}elseif(insStr.Substring(0,4)=="Queu")//获取下载文件夹请求,回复完整文件名列表{stringpath=insStr.Substring(5,insStr.Length-5)。stringlistStr=GetFileNames(path,true)。SendString(handler,listStr)。}elseif(insStr.Substring(0,4)=="upld")//收到上传文件请求{stringreFileName=insStr.Substring(5,insStr.Length-5)。LoadFile(reFileName,handler)。}elseif(insStr.Substring(0,4)=="quit")//收到断开连接命令{HostQuit()。break。}}catch{HostQuit()。break。}}}privatevoidLoadFile(stringreFileName,Sockethandler){try{FileStreamfs=newFileStream(reFileName,FileMode.Create,FileAccess.Write)。handler.Receive(buffer,8,SocketFlags.None)。//接收文件大小longfilesize=BitConverter.ToInt64(buffer,0)。longreceiveCount=0。while(receiveCount<filesize)//接收文件{intreadcount=handler.Receive(buffer,bufferSize,SocketFlags.None)。fs.Write(buffer,0,readcount)。receiveCount+=readcount。}fs.Close()。}catch{HostQuit()。}}privatevoidSendFile(stringfileNmae,Sockethandler){try{FileStreamfs=newFileStream(fileNmae,FileMode.Open,FileAccess.Read)。longsize=fs.Length。byte[]bysize=BitConverter.GetBytes(size)。handler.Send(bysize,8,SocketFlags.None)。//发送文件大小BinaryReaderbr=newBinaryReader(fs)。intsendcount=0。while(sendcount<size)//发送文件{intreadcount=br.Read(buffer,0,bufferSize)。sendcount+=readcount。handler.Send(buffer,readcount,SocketFlags.None)。}}catch{HostQuit()。}}privatevoidHostQuit(){GlobalValues.canControl.WaitOne()。GlobalValues.canControl.Release()。if(handler.Connected==true){handler.Shutdown(SocketShutdown.Both)。handler.Close()。}}privatevoidSendString(Sockethandler,stringlistStr){byte[]list=Encoding.BigEndianUnicode.GetBytes(listStr)。byte[]listcountbuffer=BitConverter.GetBytes(Convert.ToInt64(list.Length))。try{handler.Send(listcountbuffer,8,SocketFlags.None)。//发送列表大小intsendcount=0。while(sendcount<list.Length)//发送列表{if(sendcount+bufferSize<list.Length)//不是最后一次{inti=handler.Send(list,sendcount,bufferSize,SocketFlags.None)。sendcount+=i。}else{inti=handler.Send(list,sendcount,list.Length-sendcount,SocketFlags.None)。//发送最后一次sendcount+=i。}}}catch(Exceptione){MessageBox.Show("连接断开.")。}}//fileOnly=true则获取指定目录及子目录内所有文件信息,fileOnly=false则获取指定目录文件信息及文件夹信息privatestringGetFileNames(stringpath,boolfileOnly){stringlistStr=string.Empty。DirectoryInfodrct=newDirectoryInfo(path)。foreach(FileSystemInfofsiindrct.GetFileSystemInfos()){if(fsiisFileInfo){//文件FileInfofi=(FileInfo)fsi。listStr+=fi.FullName。listStr+="\n"。if(fi.Length<1024){stringsizeStr=fi.Length.ToString()+"字节"。listStr+=sizeStr。}elseif(fi.Length<1024*1024){doubletemp=Convert.ToDouble(fi.Length)/1024。stringsizeStr=string.Format("{0:F1}",temp)+"KB"。listStr+=sizeStr。}elseif(fi.Length<1024*1024*1024){doubletemp=Convert.ToDouble(fi.Length)/1024/1024。stringsizeStr=string.Format("{0:F1}",temp)+"MB"。listStr+=sizeStr。}else{doubletemp=Convert.ToDouble(fi.Length)/1024/1024/1024。stringsizeStr=string.Format("{0:F1}",temp)+"GB"。listStr+=sizeStr。}listStr+="\n"。listStr+=fi.LastWriteTime.ToString("yyyy-MM-ddhh:mm:ss")。listStr+="\n"。}elseif(fsiisDirectoryInfo){if(fileOnly){listStr+=GetFileNames(fsi.FullName,true)。}else{//文件夹DirectoryInfodi=(DirectoryInfo)fsi。listStr+=di.FullName。listStr+="\n"。listStr+="dir"。listStr+="\n"。listStr+=di.LastWriteTime.ToString("yyyy-MM-ddhh:mm:ss")。listStr+="\n"。}}}returnlistStr。}}}public服务器(){InitializeComponent()。Control.CheckForIllegalCrossThreadCalls=false。stringHostName=Dns.GetHostName()。//得到主机名IPHostEntryIpEntry=Dns.GetHostEntry(HostName)。//得到主机IPstringstrIPAddr=IpEntry.AddressList[0].ToString()。tsTxb_IPAdd.Text=strIPAddr。hostIPAddress=IPAddress.Parse(strIPAddr)。Server=newIPEndPoint(hostIPAddress,Convert.ToInt32(tsTxb_Port.Text))。sock=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)。sock.Bind(Server)。sock.Listen(10)。stringstr="正在监听端口"+tsTxb_Port.Text+"..."。tsLbl_Status.Text="状态:"+str。AcceptTh=newThread(ThAccept)。AcceptTh.Start()。//开始监听端口}//下面是监听和停止监听的按钮事件privatevoidbtn_Start_Click(objectsender,EventArgse){tsBtn_Start.Enabled=false。tsBtn_Stop.Enabled=true。Server=newIPEndPoint(hostIPAddress,Convert.ToInt32(tsTxb_Port.Text))。sock=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)。sock.Bind(Server)。sock.Listen(10)。stringstr="正在监听端口"+tsTxb_Port.Text+"..."。tsLbl_Status.Text="状态:"+str。AcceptTh=newThread(ThAccept)。AcceptTh.Start()。}privatevoidbtn_stop_Click(objectsender,EventArgse){tsBtn_Start.Enabled=true。tsBtn_Stop.Enabled=false。try{sock.Shutdown(SocketShutdown.Both)。}catch{}sock.Close()。tsLbl_Status.Text="状态:已停止监听"。}2.5.2客户(client)程序//MyThread.cs中的实现usingSystem。usingSystem.Collections.Generic。usingSystem.Linq。usingSystem.Text。usingSystem.IO。usingSystem.Net.Sockets。usingSystem.Threading。usingSystem.Windows.Fspace客户端_TCP文件传输{publicclassmyThread{ThreaddownloadTh。ThreaduploadTh。SocketwordSocket。stringfileName。stringsavePath。byte[]buffer。constintbufferSize=4096。ToolStripProgressBartspBar。ToolStripStatusLstartTime=0。longreceivecount=0。longsendCount=0。intupOrDown=1。//指示上传或下载System.Windows.Forms.Timertimer1=newSystem.Windows.Forms.Timer()。publicmyThread(SocketworkSock,stringFileName,stringSavePath,refToolStripProgressBarTspBar,refToolStripStatusLabelSpeed){wordSocket=workSock。fileName=FileName。savePath=SavePath。buffer=newbyte[bufferSize]。downloadTh=newThread(newThreadStart(Download))。uploadTh=newThread(newThreadStart(Upload))。tspBar=TspBar。speed=Speed。}publicmyThread(SocketworkSock,stringFileName,refToolStripProgressBarTspBar,refToolStripStatusLabelSpeed){wordSocket=workSock。fileName=FileName。buffer=newbyte[bufferSize]。downloadTh=newThread(newThreadStart(Download))。uploadTh=newThread(newThreadStart(Upload))。tspBar=TspBar。speed=Speed。}publicvoidStartDownload(){upOrDown=1。downloadTh.Start()。timer1.Enabled=true。timer1.Interval=100。timer1.Tick+=newEventHandler(timer1_Tick)。startTime=System.Environment.TickCount。timer1.Start()。}publicvoidStartUpload(){upOrDown=0。uploadTh.Start()。timer1.Enabled=true。timer1.Interval=50。timer1.Tick+=newEventHandler(timer1_Tick)。startTime=System.Environment.TickCount。timer1.Start()。}voidtimer1_Tick(objectsender,EventArgse){intspentTime=System.Environment.TickCount-startTime。if(spentTime!=0){if(upOrDown==1){doublesp=Convert.ToDouble(receivecount)/Convert.ToDouble(spentTime)*1000/1024。if(sp<1024)speed.Text=tspBar.Value.ToString()+"%下载速度:"+string.Format("{0:F1}",sp)+"KB"。elsespeed.Text=tspBar.Value.ToString()+"%下载速度:"+string.Format("{0:F1}",sp/1024)+"MB/S"。}else{doublesp=Convert.ToDouble(sendCount)/Convert.ToDouble(spentTime)*1000/1024。if(sp<1024)speed.Text=tspBar.Value.ToString()+"%上传速度:"+string.Format("{0:F1}",sp)+"KB"。elsespeed.Text=tspBar.Value.ToString()+"%上传速度:"+string.Format("{0:F1}",sp/1024)+"MB/S"。}}}privatevoidDownload(){try{stringins="name="+fileName。byte[]data=Encoding.BigEndianUnicode.GetBytes(ins)。wordSocket.Send(data,data.Length,SocketFlags.None)。//发送下载请求stringreFileName=savePath+"\\"+GetFileName(fileName)。Directory.CreateDirectory(savePath)。FileStreamfs=newFileStream(reFileName,FileMode.Create,FileAccess.Write)。wordSocket.Receive(buffer,8,SocketFlags.None)。//接收文件大小longfilesize=BitConverter.ToInt64(buffer,0)。while(receivecount<filesize)//接收文件{intreadcount=wordSocket.Receive(buffer,bufferSize,SocketFlags.None)。fs.Write(buffer,0,readcount)。receivecount+=readcount。tspBar.Value=Convert.ToInt32(Convert.ToDouble(receivecount)/Convert.ToDouble(filesize)*100)。}tspBar.Value=100。timer1_Tick(newobject(),newEventArgs())。fs.Close()。timer1.Stop()。StaticValue.isBusy=false。}catch{MessageBox.Show("连接断开.")。timer1.Stop()。if(wordSocket.Connected==true){wordSocket.Shutdown(SocketShutdown.Both)。wordSocket.Close()。timer1.Stop()。StaticValue.isBusy=false。}}}privatevoidUpload(){try{stringshortFileName=fileName.Substring(fileName.LastIndexOf('\\')+1,fileName.Length-fileName.LastIndexOf('\\')-1)。stringserverFileName=StaticValue.curServerPath+"\\"+shortFileName。//指定上传到服务器的哪个路径stringins="upld="+serverFileName。byte[]byins=Encoding.BigEndianUnicode.GetBytes(ins)。wordSocket.Send(byins,byins.Length,SocketFlags.None)。//发送上传请求及完整文件名FileStreamfs=newFileStream(fileName,FileMode.Open,FileAccess.Read)。longsize=fs.Length。byte[]bysize=BitConverter.GetBytes(size)。wordSocket.Send(bysize,8,SocketFlags.None)。//发送上传文件大小BinaryReaderbr=newBinaryReader(fs)。while(sendCount<size)//发送文件{intreadcount=br.Read(buffer,0,bufferSize)。sendCount+=readcount。wordSocket.Send(buffer,readcount,SocketFlags.None)。tspBar.Value=Convert.ToInt32(Convert.ToDouble(sendCount)/Convert.ToDouble(size)*100)。}tspBar.Value=100。timer1_Tick(newobject(),newEventArgs())。fs.Close()。timer1.Stop()。StaticValue.isBusy=false。}catch(Exceptione){MessageBox.Show("连接断开.")。wordSocket.Shutdown(SocketShutdown.Both)。wordSocket.Close()。timer1.Stop()。StaticValue.isBusy=false。}}publicstringGetFileName(stringfileName){returnfileName.Substring(fileName.LastIndexOf('\\')+1,fileName.Length-fileName.LastIndexOf('\\')-1)。}publicstringGetFileType(stringfileName){returnfileName.Substring(fileName.LastIndexOf('.'),fileName.Length-fileName.LastIndexOf('.'))。}}}//下面给出各按钮点击事件///<summary>///连接服务器按钮点击事件///</summary>///<paramname="sender"></param>///<paramname="e"></param>privatevoidbtn_Connect_Click(objectsender,EventArgse){hostIPAddress=IPAddress.Parse(ttxb_IPAdd.Text)。intport=Convert.ToInt32(ttxb_port.Text)。Server=newIPEndPoint(hostIPAddress,port)。sock=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)。try{sock.Connect(Server)。//连接服务器toolStripStatusLabel1.Text="与远程主机"+ttxb_IPAdd.Text+""+ttxb_port.ToString()+"连接成功"。RefreshListView(GetDtListArray("boot",false))。//获取服务器根目录connectDone=true。tsBtn_Connect.Enabled=false。tsBtn_DisConnect.Enabled=true。}catch{MessageBox.Show("连接失败.")。if(sock.Connected==true){sock.Shutdown(SocketShutdown.Both)。sock.Close()。}}}///<summary>///下载文件点击事件///</summary>///<paramname="sender"></param>///<paramname="e"></param>privatevoidbtn_GetFile_Click(objectsender,EventArgse){DownLoad(listView1)。//调用自定义方法下载文件}privatevoidDownLoad(ListViewlistView1){if(listView1.SelectedIndices.Count>0&&listView1.SelectedIndices[0]!=0)//有选定项且选定的不是"返回上层"{stringsize=listView1.SelectedItems[0].SubItems[1].Text。if(size!="")//如果选定的是文件{listView2.Items.Add(listView1.SelectedItems[0].SubItems[0].Text)。listView2.Items[listView2.Items.Count-1].SubItems.Add(size)。//将文件大小加入listViewlistView2.Items[listView2.Items.Count-1].ImageIndex=ICOSearcher.GetIcoIndex(listView1.SelectedItems[0].SubItems[0].Text)。//获取该文件的intindex=listView1.SelectedIndices[0]-1。stringFileName=fullNameList[index]。downloadItemnewfile=newdownloadItem(FileName,StaticValue.curSavePath)。downQueue.Enqueue(newfile)。}else//如果是文件夹{stringdownPath=StaticValue.curServerPath+"\\"+listView1.SelectedItems[0].SubItems[0].Text。string[]listArray=GetDtListArray(downPath,true)。Queue<downloadItem>tempQueue=GetDownFileQueue(listArray)。while(tempQueue.Count>0){downQueue.Enqueue(tempQueue.Dequeue())。}}}}///<summary>///设置保存位置的按钮点击事件///</summary>///<paramname="sender"></param>///<paramname="e"></param>{privatevoidtsBtn_savePath_Click(objectsender,EventArgse){if(folderBrowserDialog1.ShowDialog()==DialogResult.OK){StaticValue.curSavePath=folderBrowserDialog1.SelectedPath。}}///<summary>///点击断开连接的按钮事件,断开连接,并清空listView等///</summary>///<paramname="sender"></param>///<paramname="e"></param>privatevoidtsBtn_DisConnect_Click(objectsender,EventAr

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论