网络编程实验报告.docx
- 文档编号:28345975
- 上传时间:2023-07-10
- 格式:DOCX
- 页数:50
- 大小:167.99KB
网络编程实验报告.docx
《网络编程实验报告.docx》由会员分享,可在线阅读,更多相关《网络编程实验报告.docx(50页珍藏版)》请在冰豆网上搜索。
网络编程实验报告
贵州大学实验报告
学院:
计算机学院专业:
软件工程班级:
软件123班
姓名
***
学号
***
实验组
实验时间
2015-5-9
指导教师
蔡丽
成绩
实验项目名称
FTP上传下载器编程
实验目的
通过本实验掌握C#中FTP上传下载器编程的方法,了解其区别与适用场合。
实验要求
了解C#的UDP编程方法。
实验原理
使用.NET请求/响应模型的FtpWebRequest类和FtpWebResponse类实现简单的Web浏览器
实验环境
VisualStudio开发环境
实验步骤
1.设计程序界面。
2.实现程序功能。
实验内容
实现简单的Web浏览器,要求使用.NET请求/响应模型的FtpWebRequest类和FtpWebResponse类。
实验数据
服务器核心代码
//FtpServerForm类:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Globalization;
usingSystem.IO;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
usingSystem.Windows.Forms;
namespaceFtpServer
{
publicpartialclassFtpServerForm:
Form
{
TcpListenermyTcpListener=null;
privateThreadlistenThread;
//保存用户名和密码
Dictionary
publicFtpServerForm()
{
InitializeComponent();
//初始化用户名和密码
users=newDictionary
users.Add("admin","admin");
//设置默认的主目录
tbxFtpRoot.Text="F:
/MyFtpServerRoot/";
IPAddress[]ips=Dns.GetHostAddresses("");
tbxFtpServerIp.Text=ips[1].ToString();
tbxFtpServerPort.Text="21";
lstboxStatus.Enabled=false;
}
//启动服务器
privatevoidbtnFtpServerStartStop_Click(objectsender,EventArgse)
{
if(myTcpListener==null)
{
listenThread=newThread(ListenClientConnect);
listenThread.IsBackground=true;
listenThread.Start();
lstboxStatus.Enabled=true;
lstboxStatus.Items.Clear();
lstboxStatus.Items.Add("已经启动Ftp服务...");
btnFtpServerStartStop.Text="停止";
}
else
{
myTcpListener.Stop();
myTcpListener=null;
listenThread.Abort();
lstboxStatus.Items.Add("Ftp服务已停止!
");
lstboxStatus.TopIndex=lstboxStatus.Items.Count-1;
btnFtpServerStartStop.Text="启动";
}
}
//监听端口,处理客户端连接
privatevoidListenClientConnect()
{
myTcpListener=newTcpListener(IPAddress.Parse(tbxFtpServerIp.Text),int.Parse(tbxFtpServerPort.Text));
//开始监听传入的请求
myTcpListener.Start();
AddInfo("启动FTP服务成功!
");
AddInfo("Ftp服务器运行中...[点击”停止“按钮停止FTP服务]");
while(true)
{
try
{
//接收连接请求
TcpClienttcpClient=myTcpListener.AcceptTcpClient();
AddInfo(string.Format("客户端({0})与本机({1})建立Ftp连接",tcpClient.Client.RemoteEndPoint,myTcpListener.LocalEndpoint));
Useruser=newUser();
mandSession=newUserSeesion(tcpClient);
user.workDir=tbxFtpRoot.Text;
Threadt=newThread(UserProcessing);
t.IsBackground=true;
t.Start(user);
}
catch
{
break;
}
}
}
//处理客户端用户请求
privatevoidUserProcessing(objectobj)
{
Useruser=(User)obj;
stringsendString="220FTPServerv1.0";
RepleyCommandToUser(user,sendString);
while(true)
{
stringreceiveString=null;
try
{
//读取客户端发来的请求信息
receiveString=mandSession.streamReader.ReadLine();
}
catch(Exceptionex)
{
if(mandSession.tcpClient.Connected==false)
{
AddInfo(string.Format("客户端({0}断开连接!
)",mandSession.tcpClient.Client.RemoteEndPoint));
}
else
{
AddInfo("接收命令失败!
"+ex.Message);
}
break;
}
if(receiveString==null)
{
AddInfo("接收字符串为null,结束线程!
");
break;
}
AddInfo(string.Format("来自{0}:
[{1}]",mandSession.tcpClient.Client.RemoteEndPoint,receiveString));
//分解客户端发来的控制信息中的命令和参数
stringcommand=receiveString;
stringparam=string.Empty;
intindex=receiveString.IndexOf('');
if(index!
=-1)
{
command=receiveString.Substring(0,index).ToUpper();
param=receiveString.Substring(command.Length).Trim();
}
//处理不需登录即可响应的命令(这里只处理QUIT)
if(command=="QUIT")
{
//关闭TCP连接并释放与其关联的所有资源
mandSession.Close();
return;
}
else
{
switch(user.loginOK)
{
//等待用户输入用户名:
case0:
CommandUser(user,command,param);
break;
//等待用户输入密码
case1:
CommandPassword(user,command,param);
break;
//用户名和密码验证正确后登陆
case2:
switch(command)
{
case"CWD":
CommandCWD(user,param);
break;
case"PWD":
CommandPWD(user);
break;
case"PASV":
CommandPASV(user);
break;
case"PORT":
CommandPORT(user,param);
break;
case"LIST":
CommandLIST(user,param);
break;
case"NLIST":
CommandLIST(user,param);
break;
//处理下载文件命令
case"RETR":
CommandRETR(user,param);
break;
//处理上传文件命令
case"STOR":
CommandSTOR(user,param);
break;
//处理删除命令
case"DELE":
CommandDELE(user,param);
break;
//使用Type命令在ASCII和二进制模式进行变换
case"TYPE":
CommandTYPE(user,param);
break;
default:
sendString="502commandisnotimplemented.";
RepleyCommandToUser(user,sendString);
break;
}
break;
}
}
}
}
//想客户端返回响应码
privatevoidRepleyCommandToUser(Useruser,stringstr)
{
try
{
mandSession.streamWriter.WriteLine(str);
AddInfo(string.Format("向客户端({0})发送[{1}]",mandSession.tcpClient.Client.RemoteEndPoint,str));
}
catch
{
AddInfo(string.Format("向客户端({0})发送信息失败",mandSession.tcpClient.Client.RemoteEndPoint));
}
}
//向屏幕输出显示状态信息(这里使用了委托机制)
privatedelegatevoidAddInfoDelegate(stringstr);
privatevoidAddInfo(stringstr)
{
//如果调用AddInfo()方法的线程与创建ListView控件的线程不在一个线程时
//此时利用委托在创建ListView的线程上调用
if(lstboxStatus.InvokeRequired==true)
{
AddInfoDelegated=newAddInfoDelegate(AddInfo);
this.Invoke(d,str);
}
else
{
lstboxStatus.Items.Add(str);
lstboxStatus.TopIndex=lstboxStatus.Items.Count-1;
lstboxStatus.ClearSelected();
}
}
#region处理各个命令
#region登录过程,即用户身份验证过程
//处理USER命令,接收用户名但不进行验证
privatevoidCommandUser(Useruser,stringcommand,stringparam)
{
stringsendString=string.Empty;
if(command=="USER")
{
sendString="331USERcommandOK,passwordrequired.";
user.userName=param;
//设置loginOk=1为了确保后面紧接的要求输入密码
//1表示已接收到用户名,等到接收密码
user.loginOK=1;
}
else
{
sendString="501USERcommandsyntaxerror.";
}
RepleyCommandToUser(user,sendString);
}
//处理PASS命令,验证用户名和密码
privatevoidCommandPassword(Useruser,stringcommand,stringparam)
{
stringsendString=string.Empty;
if(command=="PASS")
{
stringpassword=null;
if(users.TryGetValue(user.userName,outpassword))
{
if(password==param)
{
sendString="230Userloggedinsuccess";
//2表示登录成功
user.loginOK=2;
}
else
{
sendString="530Passwordincorrect.";
}
}
else
{
sendString="530Usernameorpasswordincorrect.";
}
}
else
{
sendString="501PASScommandSyntaxerror.";
}
RepleyCommandToUser(user,sendString);
//用户当前工作目录
user.currentDir=user.workDir;
}
#endregion
#region文件管理命令
//处理CWD命令,改变工作目录
privatevoidCommandCWD(Useruser,stringtemp)
{
stringsendString=string.Empty;
try
{
stringdir=user.workDir.TrimEnd('/')+temp;
//是否为当前目录的子目录,且不包含父目录名称
if(Directory.Exists(dir))
{
user.currentDir=dir;
sendString="250Directorychangedto'"+dir+"'successfully";
}
else
{
sendString="550Directory'"+dir+"'doesnotexist";
}
}
catch
{
sendString="502Directorychangedunsuccessfully";
}
RepleyCommandToUser(user,sendString);
}
//处理PWD命令,显示工作目录
privatevoidCommandPWD(Useruser)
{
stringsendString=string.Empty;
sendString="257'"+user.currentDir+"'isthecurrentdirectory";
RepleyCommandToUser(user,sendString);
}
//处理LIST/NLIST命令,想客户端发送当前或指定目录下的所有文件名和子目录名
privatevoidCommandLIST(Useruser,stringparameter)
{
stringsendString=string.Empty;
DateTimeFormatInfodateTimeFormat=newCultureInfo("en-US",true).DateTimeFormat;
//得到目录列表
string[]dir=Directory.GetDirectories(user.currentDir);
if(string.IsNullOrEmpty(parameter)==false)
{
if(Directory.Exists(user.currentDir+parameter))
{
dir=Directory.GetDirectories(user.currentDir+parameter);
}
else
{
strings=user.currentDir.TrimEnd('/');
user.currentDir=s.Substring(0,s.LastIndexOf("/")+1);
}
}
for(inti=0;i
{
stringfolderName=Path.GetFileName(dir[i]);
DirectoryInfod=newDirectoryInfo(dir[i]);
//按下面的格式输出目录列表
sendString+=@"dwr-\t"+Dns.GetHostName()+"\t"+dateTimeFormat.GetAbbreviatedMonthName(d.CreationTime.Month)
+d.CreationTime.ToString("ddyyyy")+"\t"+folderName+Environment.NewLine;
}
//得到文件列表
string[]files=Directory.GetFiles(user.currentDir);
if(string.IsNullOrEmpty(parameter)==false)
{
if(Directory.Exists(user.currentDir+parameter+"/"))
{
files=Directory.GetFiles(user.currentDir+parameter+"/");
}
}
for(inti=0;i { FileInfof=newFileInfo(files[i]); stringfileName=Path.GetFileName(files[i]); //按下面的格式输出文件列表 sendString+="-wr-\t"+Dns.GetHostName()+"\t"+f.Length+"" +dateTimeFormat.GetAbbreviatedMonthName(f.CreationTime.Month) +f.CreationTime.ToString("ddyyyy")+"\t"+fileName+Environment.NewLine; } //List命令指示获得FTP服务器上的文件列表字符串信息 //所以调用List命令过程,客户端接受的指示一些字符串 //所以isBinary是false,代表传输的是ASCII数据 //但是为了防止isBinary因为设置user.isBinary=false而改变 //所以事先保存user.IsBinary的引用(此时为true),方便后面下载文件 boolisBinary=user.isBinary; user.isBinary=false; RepleyCommandToUser(user,"150OpeningASCIIdataconnection"); InitDataSession(user); SendByUserSession(user,sendString); RepleyCommandToUser(user,"226Transfercomplete"); user.isBinary=isBinary; } //处理RETR命令,提供下载功能,将用户请求的文件发送给用户 privatevoidCommandRETR(Useruser,stringfilename) { stringsendString=""; //下载的文件全名 stringpath=user.currentDir+filename; FileStreamfilestream=newFileStream(path,FileMode.Open,FileAccess.Read); //发送150到用户,表示服务器文件状态良好,将要打开数据连接传输文件 if(user.isBinary) { sendString="150OpeningBINARYmodedataconnectionfordownload"; } else { sendString="150OpeningASCIImodedataconnectionfordownload"; } RepleyCommandToUser(user,sendString); InitDataSession(user); SendFileByUserSession(user,filestream); RepleyCommandToUser(user,"226Transfercomplete
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 网络 编程 实验 报告
![提示](https://static.bdocx.com/images/bang_tan.gif)