我正在使用C#套接字(異步模式)並需要從流中讀取確切的字節數來正確解析消息。由於系統中的消息非常長,看起來像socket.EndRead操作返回的字節數少於socket.BeginRead中所請求的字節數。只有在讀取了確切的字節數時,纔有可能完成c#套接字標記操作?被uing的NetworkStream是這樣的??? \從c#套接字讀取確切的字節數
IAsyncRes ar = socket.BeginRead(1Mb byte message)
ar.Handle.Wait() // --> will signal ONLY when 1Mb us read !!!!
socket.EndRead()
UPD:
我已經用C#迭代器解決了這個問題。 (這裏沒有顯示它運行的irator環和負責做的MoveNext線程)
protected IEnumerator<IAsyncResult> EnumReceiveExact(byte[] array)
{
int offset = 0;
while (offset < array.Length)
{
SocketError err = SocketError.Success;
IAsyncResult ar = _socket.BeginReceive(array, offset, array.Length - offset, SocketFlags.None, out err, null, null);
Console.WriteLine("{0}:err:{1}", this, err);
if (err != SocketError.Success)
{
_socket.Close();
throw new Exception("Error " + err);
}
yield return ar;
while (!ar.IsCompleted)
{
yield return ar;
}
offset += _socket.EndReceive(ar, out err);
if (err != SocketError.Success)
{
_socket.Close();
throw new Exception("Error " + err);
}
}
}
在調用'socket.EndRead()'時,它將返回可讀取的字節數。 – Gavin
我知道,但我不想複雜的閱讀大塊的消息,有沒有一些包裝已經做到了。 – Boris
你不應該大塊閱讀它?如果你的客戶端發送1024字節,你應該「一次接收1024個字節」。 http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.endread(v=vs.80).aspx – Gavin