SslStream.BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) 方法

定义

开始一个异步写入操作,该操作从指定的缓冲区写入 Byte流。

public:
 override IAsyncResult ^ BeginWrite(cli::array <System::Byte> ^ buffer, int offset, int count, AsyncCallback ^ asyncCallback, System::Object ^ asyncState);
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState);
override this.BeginWrite : byte[] * int * int * AsyncCallback * obj -> IAsyncResult
Public Overrides Function BeginWrite (buffer As Byte(), offset As Integer, count As Integer, asyncCallback As AsyncCallback, asyncState As Object) As IAsyncResult

参数

buffer
Byte[]

一个 Byte 数组,提供要写入流中的字节。

offset
Int32

从零开始读取要写入流的字节的位置 buffer

count
Int32

一个 Int32 值,该值指定要从 buffer中读取的字节数。

asyncCallback
AsyncCallback

一个 AsyncCallback 委托,该委托引用在写入操作完成时要调用的方法。

asyncState
Object

一个用户定义的对象,其中包含有关写入操作的信息。 此操作完成后,此对象将 asyncCallback 传递给委托。

返回

一个 IAsyncResult 对象,指示异步操作的状态。

例外

buffernull

offset 小于零。

-或-

offset 大于长度 buffer

-或-

offset + count 大于长度 buffer

写入操作失败。

正在进行写入操作。

此对象已关闭。

身份验证未发生。

示例

下面的代码示例演示如何调用此方法。

void ReadCallback(IAsyncResult ar)
{
    ClientState state = (ClientState) ar.AsyncState;
    SslStream stream = state.stream;
    // Read the  message sent by the client.
    // The end of the message is signaled using the
    // "<EOF>" marker.
    int byteCount = -1;
    try
    {
        Console.WriteLine("Reading data from the client.");
        byteCount = stream.EndRead(ar);
        // Use Decoder class to convert from bytes to UTF8
        // in case a character spans two buffers.
        Decoder decoder = Encoding.UTF8.GetDecoder();
        char[] chars = new char[decoder.GetCharCount(state.buffer,0, byteCount)];
        decoder.GetChars(state.buffer, 0, byteCount, chars,0);
        state.readData.Append (chars);
        // Check for EOF or an empty message.
        if (state.readData.ToString().IndexOf("<EOF>") == -1 && byteCount != 0)
        {
            // We are not finished reading.
            // Asynchronously read more message data from  the client.
            stream.BeginRead(state.buffer, 0, state.buffer.Length,
                new AsyncCallback(ReadCallback),
                state);
        }
        else
        {
            Console.WriteLine("Message from the client: {0}", state.readData.ToString());
        }

        // Encode a test message into a byte array.
        // Signal the end of the message using "<EOF>".
        byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>");
        // Asynchronously send the message to the client.
        stream.BeginWrite(message, 0, message.Length,
            new AsyncCallback(WriteCallback),
            state);
    }
    catch (Exception readException)
    {
        Console.WriteLine("Read error: {0}", readException.Message);
        state.Close();
        return;
    }
}

适用于