我一直致力于一个文件共享应用程序,它可以对任何大小的文件进行分块,序列化每个块并使用TCP连接有序地发送它。但是在两个系统之间接收时出现问题,错误显示“输入流不是有效的二进制格式。起始内容(以字节为单位)为:0D-0A-00-01-00-00-00-FF- FF-FF-FF-01-00-00-00-00-00“但发送方发送适当的字节数。是因为我使用网络流的beginRead和beginWrite方法还是什么?请问我做错了什么? 我的客户代码。
public void SendMessage(string path)
{
NetworkStream file = new NetworkStream(client);
try {
foreach (Chunk item in ChunkAlgorithm.ReadChunk(path))
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter serialize = new BinaryFormatter();
serialize.Serialize(stream, item);
stream.Seek(0, SeekOrigin.Begin);
SentBytes = stream.ToArray();
file.BeginWrite(SentBytes, 0, SentBytes.Length, MessageSentCallBack, null);
//Console.WriteLine($"sent: {SentBytes.Length} bytes");
Thread.Sleep(1);
}
}
Console.WriteLine("Done sending bytes");
}catch(Exception ex)
{
Console.WriteLine($"ERROR OCURRED: {ex.Message}");
}
//client.BeginSend(empty, 0, 0, 0, MessageSentCallBack, null);
}
我的服务器代码。
public void StartReceiving()
{
file.BeginRead(receivingBytes, 0, receivingBytes.Length, ReceivedCallBack,null);
}
private void ReceivedCallBack(IAsyncResult ar)
{
try {
string savepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test1.mp4");
int receivedLength = file.EndRead(ar);
using (MemoryStream stream = new MemoryStream(receivingBytes))
{
BinaryFormatter formatter = new BinaryFormatter();
Chunk ReceivedChunk = formatter.Deserialize(stream) as Chunk;
if (ReceivedChunk.LastChunk)
{
ChunkList.Add(ReceivedChunk);
Console.WriteLine($"Received Chunk: {ReceivedChunk.chunkCount} of {receivedLength} bytes");
couple(ChunkList, savepath);
}
else
{
ChunkList.Add(ReceivedChunk);
Console.WriteLine($"Received Chunk: {ReceivedChunk.chunkCount} of {receivedLength} bytes");
}
}
Thread.Sleep(1);
StartReceiving();
}catch(Exception ex)
{
Console.WriteLine($"ERROR OCURRED: {ex.Message}");
}
}
private static void couple(List<Chunk> ChunkList,string savepath)
{
Console.WriteLine("Coupling...");
ChunkAlgorithm.couple(ChunkList, savepath);
Console.WriteLine("Coupling Done...");
Console.WriteLine("Received All Data...");
}