我有 2 个应用程序,一个是服务器应用程序,另一个是客户端应用程序。两者都在同一台计算机上。客户端有一个按钮。单击此按钮时,客户端开始从服务器下载文件。问题是,有时客户端成功接收所有文件,但有时客户端只收到第一个文件然后停止传输。下面的代码有问题吗?任何人都可以告诉我我哪里错了吗?我只是这样编码的新手。非常感谢您的帮助。提前致谢。这是代码:
当用户单击客户端上的按钮时,客户端将从服务器发送请求下载文件:
//client side
sendRequest("requestFiles ");
服务器收到令牌 requestFiles 后会准备文件供客户端下载
// server side
if (execmd == "requestFiles")
{
string[] fList = Directory.GetFiles(folderDir);
for (int i = 0; i < fList.Length; i++)
{
FileInfo fi = new FileInfo(fList[i]);
string[] mDesc = new string[3];
mDesc[0] = fi.Name;
mDesc[1] = fi.Length.ToString();
mDesc[2] = fi.FullName;
string fileSend = "CommitRequest " + fi.Name + " " + fi.Length.ToString() + " " + usID + " " + mName;
sendRequest(fileSend);
ClientDownloadingFromServer(mDesc[2], mDesc[1], sock);
}
sendComment("AllUpDone");
continue;
}
对于每个需要上传的文件,服务器将发送一个令牌 CommitRequest,其中包含文件的详细信息(名称、大小) 当客户端收到 CommitRequest 时:
//client side
if (execmd == "CommitRequest")
{
//get file name and file size
downloadFileFromServer(sock);
continue;
}
客户端的方法downloadFileFromServer:
//client side
private void downloadMapFromServer(Socket s)
{
Socket sock = s;
//prepare directory rootDir to store file
System.IO.FileStream fout = new System.IO.FileStream(rootDir + "\\" + fileN, FileMode.Create, FileAccess.Write);
NetworkStream nfs = new NetworkStream(sock);
long size = int.Parse(fileS);
long rby = 0;
try
{
//loop till the Full bytes have been read
while (rby < size)
{
byte[] buffer = new byte[1024];
//Read from the Network Stream
int i = nfs.Read(buffer, 0, buffer.Length);
fout.Write(buffer, 0, (int)i);
rby = rby + i;
}
fout.Close();
}
catch (Exception ed)
{
Console.WriteLine("A Exception occured in file transfer" + ed.ToString());
MessageBox.Show(ed.Message);
}
}
服务器端的方法clientDownloadFromServer:
//server side
void ClientDownloadingFromServer(string fiPath, string fiSize, Socket s)
{
string parm1 = fiPath;
string parm2 = fiSize;
try
{
FileInfo ftemp = new FileInfo(parm1);
long total=ftemp.Length;
long rdby=0 ;
int len=0 ;
byte[] buffed = new byte[1024] ;
// Open the file requested for download
System.IO.FileStream fin = new System.IO.FileStream(parm1,FileMode.Open , FileAccess.Read) ;
NetworkStream nfs = new NetworkStream(sock) ;
while(rdby < total && nfs.CanWrite)
{
//Read from the File (len contains the number of bytes read)
len =fin.Read(buffed,0,buffed.Length) ;
//Write the Bytes on the Socket
nfs.Write(buffed, 0,len);
//Increase the bytes Read counter
rdby=rdby+len ;
}
fin.Close();
}
}