我有一个客户端服务器情况,客户端将数据(例如电影)发送到服务器,服务器将该数据保存到 HDD。
它通过固定的字节数组发送数据。发送完字节后,服务器会询问是否还有更多,如果有,则发送更多等等。一切进展顺利,所有数据都得到了传递。
但是当我尝试播放电影时,它无法播放,如果我查看每部电影(客户端和服务器)的文件长度,则服务器电影大于客户端电影。当我查看最后的命令屏幕时在发送/接收数据中,跨越的字节数超过 100%。
我唯一能想到的可能是错误的事实是,我的服务器在流中读取直到固定缓冲区数组已满,因此最后的字节数比客户端多。但是,如果这是问题,我该如何解决?
我刚刚添加了两种发送方法,因为 tcp 连接有效,欢迎任何帮助。
客户
public void SendData(NetworkStream nws, StreamReader sr, StreamWriter sw)
{
using (FileStream reader = new FileStream(this.path, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[1024];
int currentBlockSize = 0;
while ((currentBlockSize = reader.Read(buffer, 0, buffer.Length)) > 0)
{
sw.WriteLine(true.ToString());
sw.Flush();
string wait = sr.ReadLine();
nws.Write(buffer, 0, buffer.Length);
nws.Flush();
label1.Text = sr.ReadLine();
}
sw.WriteLine(false.ToString());
sw.Flush();
}
}
服务器
private void GetMovieData(NetworkStream nws, StreamReader sr, StreamWriter sw, Film filmInfo)
{
Console.WriteLine("Adding Movie: {0}", filmInfo.Titel);
double persentage = 0;
string thePath = this.Path + @"\films\" + filmInfo.Titel + @"\";
Directory.CreateDirectory(thePath);
thePath += filmInfo.Titel + filmInfo.Extentie;
try
{
byte[] buffer = new byte[1024]; //1Kb buffer
long fileLength = filmInfo.TotalBytes;
long totalBytes = 0;
using (FileStream writer = new FileStream(thePath, FileMode.CreateNew, FileAccess.Write))
{
int currentBlockSize = 0;
bool more;
sw.WriteLine("DATA");
sw.Flush();
more = Convert.ToBoolean(sr.ReadLine());
while (more)
{
sw.WriteLine("SEND");
sw.Flush();
currentBlockSize = nws.Read(buffer, 0, buffer.Length);
totalBytes += currentBlockSize;
writer.Write(buffer, 0, currentBlockSize);
persentage = (double)totalBytes * 100.0 / fileLength;
Console.WriteLine(persentage.ToString());
sw.WriteLine("MORE");
sw.Flush();
string test = sr.ReadLine();
more = Convert.ToBoolean(test);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}