简单情况:
Socket 上的客户端将格式的文件(数据)的片段(例如,256 字节)发送byte []
到服务器。服务器异步接收数据。如何确定文件(数据)何时传输完毕?(服务器端)
这是服务器端负责接收数据的代码
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
BinaryWriter writer = new BinaryWriter(File.Open(@"D:\test.png", FileMode.Append));
writer.Write(state.buffer, 0, bytesRead);
writer.Close();
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket!",
bytesRead);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
有没有一种方法可以进行以下操作?
if (bytesRead > 0)
{
....
if(state.buffer!=end of receive)
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
或者,我可能会尝试向这个byte[]
对象添加一些信息(例如,一些带有标签的字符串<EOF>
),但我必须在每个步骤中分析这些信息。我可以更简单地做这个检查吗?如何做?或者使用其他方式...