在异步回调中从NetworkStream读取缓冲区

时间:2019-04-05 11:54:17

标签: c# networkstream

另请参见Understand the NetworkStream.EndRead() example from MSDN

我正在尝试使用BeginReadEndRead方法从NetworkStream异步读取(具体来说,我想打开NetworkStream,执行其他各种任务,然后处理在NetworkStream)。正如链接的问题所指出的,EndReadhere)的MSDN示例存在各种问题,并且无法正常运行。该问题的答案显示了基本代码的结构,但不包括在回调中从NetworkStream实际读取数据。

在回调函数中,如何将从NetworkStream读取的数据传输到缓冲区中?

编辑

这是原始的MSDN示例。

public static void myReadCallBack(IAsyncResult ar )
{
    NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState;
    byte[] myReadBuffer = new byte[1024];
    String myCompleteMessage = "";
    int numberOfBytesRead;

    numberOfBytesRead = myNetworkStream.EndRead(ar);
    myCompleteMessage = String.Concat(myCompleteMessage,Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));    

    // message received may be larger than buffer size so loop through until you have it all.
    while(myNetworkStream.DataAvailable)
    {
        myNetworkStream.BeginRead(myReadBuffer, 0, myReadBuffer.Length, new AsyncCallback(NetworkStream_ASync_Send_Receive.myReadCallBack), myNetworkStream);  
    }

    // Print out the received message to the console.
    Console.WriteLine("You received the following message : " + myCompleteMessage);
}

此示例的基本问题是没有数据从NetworkStream传输到myReadBuffer

编辑1

感谢Dmytro Mukalov,以下代码有效:

internal class CallbackArgs
{
    public NetworkStream Stream { get; set; }
    public byte[] Buffer { get; set; }

    public CallbackArgs(NetworkStream stream, byte[] buffer)
    {
        Stream = stream;
        Buffer = buffer;
    }
}

//  In the caller:

    //  (Create and open thisNetworkStream, and check thisNetworkStream.CanRead)

    byte[] thisReadBuffer = new byte[1024];
    CallbackArgs args = new CallbackArgs(thisNetworkStream, thisReadBuffer);
    thisNetworkStream.BeginRead(thisReadBuffer, 0, thisReadBuffer.Length, new AsyncCallback(myReadCallBack), args);

//  The callback function:
public static void myReadCallBack(IAsyncResult ar)
{
    CallbackArgs args = (CallbackArgs)ar.AsyncState;
    NetworkStream myNetworkStream = args.Stream;
    byte[] myReadBuffer = args.Buffer;

    //  myReadBuffer now contains the data read from the network stream.

    int bytesRead = myNetworkStream.EndRead(ar);

    //  Do work on myReadBuffer, etc.
}

1 个答案:

答案 0 :(得分:1)

在执行回调时,数据已经传输到传递给先前BeginRead调用的缓冲区中。给定示例的问题在于它试图使用本地myReadBuffer缓冲区读取初始消息。相反,您应该使BeginRead可以使用传递到EndRead的缓冲区。您可以通过使其成为该缓冲区的类的实例成员,将其与NetworkStream作为state的{​​{1}}参数一起传递来实现,并在某些方法中使用闭包变量来启动阅读循环等。