PipeStream.Read 메서드

정의

오버로드

Read(Span<Byte>)

현재 스트림에서 바이트 시퀀스를 읽고, 이를 바이트 배열에 쓰고, 읽은 바이트 수만큼 스트림에서 위치를 앞으로 이동합니다.

Read(Byte[], Int32, Int32)

스트림에서 바이트 블록을 읽고 지정된 길이에 대해 지정된 위치에서 시작하는 지정 버퍼에 데이터를 씁니다.

Read(Span<Byte>)

현재 스트림에서 바이트 시퀀스를 읽고, 이를 바이트 배열에 쓰고, 읽은 바이트 수만큼 스트림에서 위치를 앞으로 이동합니다.

public:
 override int Read(Span<System::Byte> buffer);
public override int Read (Span<byte> buffer);
override this.Read : Span<byte> -> int
Public Overrides Function Read (buffer As Span(Of Byte)) As Integer

매개 변수

buffer
Span<Byte>

메모리 영역입니다. 이 메서드가 반환될 때 이 영역의 내용은 현재 소스에서 읽은 바이트로 대체됩니다.

반환

Int32

buffer로 읽어온 총 바이트 수입니다. 많은 바이트가 현재 사용 가능하지 않은 경우 buffer에 할당된 바이트 수보다 적을 수 있으며 스트림의 끝에 도달하면 0이 됩니다.

예외

읽은 바이트 수가 버퍼 길이보다 깁니다.

스트림이 읽기를 지원하지 않습니다.

닫힌 파이프에는 액세스할 수 없습니다.

파이프가 아직 연결되지 않았습니다.

또는

파이프 연결이 끊어진 상태입니다.

또는

파이프 핸들이 설정되지 않은 경우 (PipeStream 구현이 InitializeHandle(SafePipeHandle, Boolean, Boolean)을 호출했습니까?

설명

현재 PipeStream 개체가 CanRead 읽기 작업을 지원하는지 여부를 확인하려면 이 속성을 사용합니다.

메서드를 ReadAsync 사용하여 현재 스트림에서 비동기적으로 읽습니다.

이 메서드는 현재 스트림에서 최대 buffer.Length 바이트를 읽고 저장 buffer합니다. 스트림 내의 현재 위치는 읽은 바이트 수에 따라 고급입니다. 그러나 예외가 발생하면 스트림 내의 현재 위치는 변경되지 않습니다.

이 메서드는 데이터를 사용할 수 없는 경우 하나 이상의 데이터를 읽을 수 있을 때까지 차단됩니다.

이 메서드는 스트림에 더 이상 데이터가 없고 더 이상 필요하지 않은 경우에만 0을 반환합니다(예: 닫힌 소켓 또는 파일의 끝).

이 메서드는 스트림의 끝에 도달하지 않은 경우에도 요청된 것보다 적은 바이트를 자유롭게 반환할 수 있습니다.

기본 데이터 형식을 읽는 데 사용합니다 BinaryReader .

적용 대상

Read(Byte[], Int32, Int32)

스트림에서 바이트 블록을 읽고 지정된 길이에 대해 지정된 위치에서 시작하는 지정 버퍼에 데이터를 씁니다.

public:
 override int Read(cli::array <System::Byte> ^ buffer, int offset, int count);
public override int Read (byte[] buffer, int offset, int count);
[System.Security.SecurityCritical]
public override int Read (byte[] buffer, int offset, int count);
override this.Read : byte[] * int * int -> int
[<System.Security.SecurityCritical>]
override this.Read : byte[] * int * int -> int
Public Overrides Function Read (buffer As Byte(), offset As Integer, count As Integer) As Integer

매개 변수

buffer
Byte[]

이 메서드는 지정된 바이트 배열의 값이 offset과 (offset + count - 1) 사이에서 현재 원본으로부터 읽어온 바이트로 교체된 상태로 반환됩니다.

offset
Int32

읽은 바이트를 배치할 buffer 배열의 바이트 오프셋입니다.

count
Int32

읽을 최대 바이트 수입니다.

반환

Int32

buffer로 읽어들인 바이트의 총 수입니다. 이 값은 현재 사용 가능한 바이트 수가 부족한 경우 요청된 바이트 수보다 작을 수 있으며, 스트림의 끝에 도달하면 0이 됩니다.

특성

예외

buffer이(가) null인 경우

offset 가 0보다 작습니다.

또는 count 가 0보다 작습니다.

countbuffer에서 사용 가능한 바이트의 수보다 큽니다.

파이프가 닫혔습니다.

파이프에서 읽기 작업을 지원하지 않는 경우

파이프의 연결이 끊겼거나 연결을 기다리는 중이거나 핸들이 설정되지 않았습니다.

I/O 오류가 발생한 경우

예제

다음 예제에서는 익명 파이프 클라이언트 및 파이프 서버를 만듭니다. 파이프 서버는 이 메서드를 Read 사용하여 파이프 클라이언트에서 일련의 바이트를 유효성 검사 코드로 읽습니다. 파이프 클라이언트와 파이프 서버는 모두 동일한 예제의 일부입니다. 예제의 서버 부분은 클라이언트 프로세스를 만들고 익명 파이프 핸들을 인수로 전달합니다.

#using <System.dll>
#using <System.Core.dll>

using namespace System;
using namespace System::IO;
using namespace System::IO::Pipes;
using namespace System::Diagnostics;

ref class PipeStreamExample
{
private:
    static array<Byte>^ matchSign = {9, 0, 9, 0};

public:
    static void Main()
    {
        array<String^>^ args = Environment::GetCommandLineArgs();
        if (args->Length < 2)
        {
            Process^ clientProcess = gcnew Process();

            clientProcess->StartInfo->FileName = Environment::CommandLine;

            AnonymousPipeServerStream^ pipeServer =
                gcnew AnonymousPipeServerStream(PipeDirection::In,
                HandleInheritability::Inheritable);
            // Pass the client process a handle to the server.
            clientProcess->StartInfo->Arguments = pipeServer->GetClientHandleAsString();
            clientProcess->StartInfo->UseShellExecute = false;
            Console::WriteLine("[SERVER] Starting client process...");
            clientProcess->Start();

            pipeServer->DisposeLocalCopyOfClientHandle();

            try
            {
                if (WaitForClientSign(pipeServer))
                {
                    Console::WriteLine("[SERVER] Valid sign code received!");
                }
                else
                {
                    Console::WriteLine("[SERVER] Invalid sign code received!");
                }
            }
            catch (IOException^ e)
            {
                 Console::WriteLine("[SERVER] Error: {0}", e->Message);
            }
            clientProcess->WaitForExit();
            clientProcess->Close();
            Console::WriteLine("[SERVER] Client quit. Server terminating.");
        }
        else
        {
            PipeStream^ pipeClient =
                gcnew AnonymousPipeClientStream(PipeDirection::Out, args[1]);
            try
            {
                Console::WriteLine("[CLIENT] Sending sign code...");
                SendClientSign(pipeClient);
            }
            catch (IOException^ e)
            {
                Console::WriteLine("[CLIENT] Error: {0}", e->Message);
            }
            Console::WriteLine("[CLIENT] Terminating.");
        }
    }

private:
    static bool WaitForClientSign(PipeStream^ inStream)
    {
        array<Byte>^ inSign = gcnew array<Byte>(matchSign->Length);
        int len = inStream->Read(inSign, 0, matchSign->Length);
        bool valid = len == matchSign->Length;

        while (valid && len-- > 0)
        {
            valid = valid && (matchSign[len] == inSign[len]);
        }
        return valid;
    }

    static void SendClientSign(PipeStream^ outStream)
    {
        outStream->Write(matchSign, 0, matchSign->Length);
    }
};

int main()
{
    PipeStreamExample::Main();
}
using System;
using System.IO;
using System.IO.Pipes;
using System.Diagnostics;

class PipeStreamExample
{
    private static byte[] matchSign = {9, 0, 9, 0};

    public static void Main()
    {
        string[] args = Environment.GetCommandLineArgs();
        if (args.Length < 2)
        {
            Process clientProcess = new Process();

            clientProcess.StartInfo.FileName = Environment.CommandLine;

            using (AnonymousPipeServerStream pipeServer =
                new AnonymousPipeServerStream(PipeDirection.In,
                HandleInheritability.Inheritable))
            {
                // Pass the client process a handle to the server.
                clientProcess.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
                clientProcess.StartInfo.UseShellExecute = false;
                Console.WriteLine("[SERVER] Starting client process...");
                clientProcess.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    if (WaitForClientSign(pipeServer))
                    {
                        Console.WriteLine("[SERVER] Valid sign code received!");
                    }
                    else
                    {
                        Console.WriteLine("[SERVER] Invalid sign code received!");
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }
            clientProcess.WaitForExit();
            clientProcess.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
        }
        else
        {
            using (PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, args[1]))
            {
                try
                {
                    Console.WriteLine("[CLIENT] Sending sign code...");
                    SendClientSign(pipeClient);
                }
                catch (IOException e)
                {
                     Console.WriteLine("[CLIENT] Error: {0}", e.Message);
                }
            }
            Console.WriteLine("[CLIENT] Terminating.");
        }
    }

    private static bool WaitForClientSign(PipeStream inStream)
    {
        byte[] inSign = new byte[matchSign.Length];
        int len = inStream.Read(inSign, 0, matchSign.Length);
        bool valid = len == matchSign.Length;

        while (valid && len-- > 0)
        {
            valid = valid && (matchSign[len] == inSign[len]);
        }
        return valid;
    }

    private static void SendClientSign(PipeStream outStream)
    {
        outStream.Write(matchSign, 0, matchSign.Length);
    }
}
Imports System.IO
Imports System.IO.Pipes
Imports System.Diagnostics

Class PipeStreamExample
    Private Shared matchSign() As Byte = {9, 0, 9, 0}

    Public Shared Sub Main()
        Dim args() As String = Environment.GetCommandLineArgs()
        If args.Length < 2 Then
            Dim clientProcess As New Process()

            clientProcess.StartInfo.FileName = Environment.CommandLine

            Using pipeServer As New AnonymousPipeServerStream( _
                PipeDirection.In, HandleInheritability.Inheritable)

                ' Pass the client process a handle to the server.
                clientProcess.StartInfo.Arguments = pipeServer.GetClientHandleAsString()
                clientProcess.StartInfo.UseShellExecute = false
                Console.WriteLine("[SERVER] Starting client process...")
                clientProcess.Start()

                pipeServer.DisposeLocalCopyOfClientHandle()

                Try
                    If WaitForClientSign(pipeServer) Then
                        Console.WriteLine("[SERVER] Valid sign code received!")
                    Else
                        Console.WriteLine("[SERVER] Invalid sign code received!")
                    End If
                Catch e As IOException
                    Console.WriteLine("[SERVER] Error: {0}", e.Message)
                End Try
            End Using
            clientProcess.WaitForExit()
            clientProcess.Close()
            Console.WriteLine("[SERVER] Client quit. Server terminating.")
        Else
            Using pipeClient As PipeStream = New AnonymousPipeClientStream(PipeDirection.Out, args(1))
                Try
                    Console.WriteLine("[CLIENT] Sending sign code...")
                    SendClientSign(pipeClient)
                Catch e As IOException
                    Console.WriteLine("[CLIENT] Error: {0}", e.Message)
                End Try
            End Using
            Console.WriteLine("[CLIENT] Terminating.")
        End If
    End Sub

    Private Shared Function WaitForClientSign(inStream As PipeStream) As Boolean
        Dim inSign() As Byte = Array.CreateInstance(GetType(Byte), matchSign.Length)
        Dim len As Integer = inStream.Read(inSign, 0, matchSign.Length)
        Dim valid = len.Equals(matchSign.Length)

        While len > 0
            len -= 1
            valid = valid And (matchSign(len).Equals(inSign(len)))
        End While
        Return valid
    End Function

    Private Shared Sub SendClientSign(outStream As PipeStream)
        outStream.Write(matchSign, 0, matchSign.Length)
    End Sub
End Class

설명

현재 PipeStream 개체가 CanRead 읽기 작업을 지원하는지 여부를 확인하려면 이 속성을 사용합니다.

Read 바이트를 읽거나 스트림의 끝에 도달할 때까지 count 메서드 블록을 호출합니다. 비동기 읽기 작업의 경우 다음을 참조 BeginRead 하세요 EndRead.

적용 대상