我有一个客户端服务器的情况,客户端将数据(例如电影)发送到服务器,服务器将该数据保存到HDD。通过TCP发送数据
它通过固定的字节数组发送数据。发送字节后,服务器询问是否有更多,如果是的话,发送更多等等。每件事情都进展顺利,所有的数据都得到了解决。
但是当我尝试播放电影时,它无法播放,如果我查看每个电影(客户端和服务器)的文件长度,则服务器电影比客户端电影更大,当我查看命令时屏幕在发送/接收数据的末尾有多于100%的字节。
我能想到的唯一可能是错误的事实是,我的服务器读取流,直到固定的缓冲区数组已满,因此在最后有更多的字节,然后客户端。但是,如果这是问题,我该如何解决这个问题?
我刚刚加了2个方法发送,因为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());
}
}
,缓冲区中剩余的字节不会是零,他们将以前的内容缓冲区。 – svick