[英]C# tcp socket client server transfer multiple files problem
我有2个应用程序,一个是服务器应用程序,另一个是客户端应用程序。 两者都在同一台计算机上。客户端有一个按钮。 单击此按钮后,客户端开始从服务器下载文件。 问题是,有时客户端成功接收了所有文件,但有时客户端仅接收了第一个文件,然后停止传输。 下面的代码有什么问题吗? 谁能告诉我我哪里错了? 我只是这样的新手。 非常感谢帮助。 提前致谢。 这是代码:
当用户单击客户端上的按钮时,客户端将从服务器发送请求下载文件:
//client side
sendRequest("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();
}
}
问题与将接收字节视为文件字节或令牌字节有关。 您的客户端代码正在尝试读取等于缓冲区大小的字节。 服务器依次发送“ CommitRequest”令牌和文件字节。 因此,假设第一个文件大小为1200个字节。 服务器将发送这1200个字节,后跟第二个文件的“ CommitRequest”,然后是第二个文件的字节。 现在,客户端将读取1024个字节的第一个文件。 然后它将读取下一个1024字节-但是这些字节将包含第一个文件的剩余176个字节,服务器的“ CommitRequest”响应以及第二个文件的前几个字节。 您的客户端代码仅占用前176个字节,而忽略下一个将包含下一个文件数据的字节。
您可以通过两种方式解决该问题-通过确保将处理剩余的字节(这可能很棘手,因为剩余的字节可能部分地具有“ CommitRequest”响应),或者重新构造您的解决方案,以便仅启动每个文件传输在客户要求之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.