[英]Reading exact number of bytes from c# socket
我正在使用C#套接字(异步模式),并且需要从流中读取确切的字节数才能正确解析消息。 由于我们系统中的消息非常长,因此好像socket.EndRead操作返回的字节数少于socket.BeginRead请求的字节数。 仅当读取了确切的字节数时,才有机会使c#套接字标记操作完成吗??? 是使用NetworkStream的方式吗?
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);
}
}
}
与枚举器进行良好的调用,尽管我希望您的外部代码不只是在asyncresults上调用WaitOne,因为这会阻塞正在运行的线程。
如果您喜欢这种风格的异步编码,请在NuGet上查看Wintellect AsyncEnumerator-它也使用迭代器,使代码具有很高的资源效率,并添加了更轻松的方式来处理取消和异常,同时确保所有APM结束方法都被调用。
我之前通过以下方式解决了确切的阅读问题:
1)在套接字上发送的数据上添加长度前缀
2)使用以下方法定义在Socket上工作的帮助程序类:
public IAsyncResult BeginRead(AsyncCallback callback)
// Calculate whether to read length header or remaining payload bytes
// Issue socket recieve and return its IAsyncResult
public MemoryStream EndRead(IAsyncResult result)
// Process socket read, if payload read completely return as a memorystream
// If length header has been recieved make sure buffer is big enough
// If 0 bytes recieved, throw SocketException(10057) as conn is closed
public IAsyncResult BeginSend(AsyncCallback callback, MemoryStream data)
// Issue sends for the length header or payload (data.GetBuffer()) on the first call
public Boolean EndSend(IAsyncResult result)
// Process bytes sent, return true if payload sent completely.
// If 0 bytes sent, throw SocketException(10057)
因此它仍然需要在循环中调用,但是看起来像一个普通的异步操作,例如,通过asyncenumerator调用(没有取消检查和异常处理):
do
{
socketHelper.BeginSend(ae.End(1, ar => socketHelper.EndSend(ar)), sendData);
yield return 1;
doneSend = socketHelper.EndSend(ae.DequeueAsyncResult());
}
while (!doneSend);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.