文本文件似乎没问题。这是用于发送文件的代码:
System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
double done = 0;
double tot = info.Length;
double chunk = 8096;
while (done < tot)
{
if (chunk > tot - done)
{
chunk = tot - done;
}
Byte[] buffer = new Byte[(int)chunk];
reader.Read(buffer,(int)done,(int)chunk);
sock.Send(buffer);
done += chunk;
statusTxt.Text = Math.Round(done / tot * 100, 2).ToString() + "%";
}
接收文件的代码非常相似:
private void ReceiveFile(string file, Socket sock,double size)
{
while (done < size)
{
if (chunk > (size - done))
{
chunk = size - done;
}
Byte[] buffer = new Byte[(int)chunk];
int count = sock.Receive(buffer);
writer.Write(buffer);
done += count;
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate()
{
foreach (TextBlock block in files.Items)
{
if (block.Tag.ToString() == file)
{
block.Text = "Uploading " + file + "... 0% ("+done.ToString()+"/" + size.ToString() + ")";
}
}
});
}
writer.Flush();
writer.Close();
}
我看过很多关于图像伪影的帖子,但所有问题都涉及到将字节编码为文本的问题。我相信我已经避免了这个问题。我在整个过程中使用字节数组,并跟踪正在读取的字节数,但图像最终仍然损坏。我检查了文件,它们在客户端和服务器上包含相同数量的字节,所以服务器上发生了一些事情,但它只是不正确。代码有什么问题,或者可能是服务器问题?