BufferedStream 클래스

정의

다른 스트림에서 작업을 읽고 쓰기 위한 버퍼링 레이어를 추가합니다.Adds a buffering layer to read and write operations on another stream. 이 클래스는 상속될 수 없습니다.This class cannot be inherited.

public ref class BufferedStream sealed : System::IO::Stream
public sealed class BufferedStream : System.IO.Stream
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class BufferedStream : System.IO.Stream
type BufferedStream = class
    inherit Stream
Public NotInheritable Class BufferedStream
Inherits Stream
상속
BufferedStream
상속
특성

예제

다음 코드 예제에서는 NetworkStream 클래스를 통해 BufferedStream 클래스를 사용 하 여 특정 i/o 작업의 성능을 향상 시키는 방법을 보여 줍니다.The following code examples show how to use the BufferedStream class over the NetworkStream class to increase the performance of certain I/O operations. 클라이언트를 시작 하기 전에 원격 컴퓨터에서 서버를 시작 합니다.Start the server on a remote computer before starting the client. 클라이언트를 시작할 때 명령줄 인수 형태로 원격 컴퓨터 이름을 지정 합니다.Specify the remote computer name as a command-line argument when starting the client. dataArraySizestreamBufferSize 상수를 변경 하 여 성능에 대 한 영향을 확인 합니다.Vary the dataArraySize and streamBufferSize constants to view their effect on performance.

첫 번째 예제에서는 클라이언트에서 실행 되는 코드를 보여 줍니다. 및 두 번째 예제에는 서버에서 실행 되는 코드를 보여 줍니다.The first example shows the code that runs on the client, and the second example shows the code that runs on the server.

예제 1: 클라이언트에서 실행 되는 코드Example 1: Code that runs on the client

#using <system.dll>

using namespace System;
using namespace System::IO;
using namespace System::Globalization;
using namespace System::Net;
using namespace System::Net::Sockets;
static const int streamBufferSize = 1000;
public ref class Client
{
private:
   literal int dataArraySize = 100;
   literal int numberOfLoops = 10000;
   Client(){}


public:
   static void ReceiveData( Stream^ netStream, Stream^ bufStream )
   {
      DateTime startTime;
      Double networkTime;
      Double bufferedTime = 0;
      int bytesReceived = 0;
      array<Byte>^receivedData = gcnew array<Byte>(dataArraySize);
      
      // Receive data using the NetworkStream.
      Console::WriteLine( "Receiving data using NetworkStream." );
      startTime = DateTime::Now;
      while ( bytesReceived < numberOfLoops * receivedData->Length )
      {
         bytesReceived += netStream->Read( receivedData, 0, receivedData->Length );
      }

      networkTime = (DateTime::Now - startTime).TotalSeconds;
      Console::WriteLine( "{0} bytes received in {1} seconds.\n", bytesReceived.ToString(), networkTime.ToString(  "F1" ) );
      
      // Receive data using the BufferedStream.
      Console::WriteLine(  "Receiving data using BufferedStream." );
      bytesReceived = 0;
      startTime = DateTime::Now;
      while ( bytesReceived < numberOfLoops * receivedData->Length )
      {
         bytesReceived += bufStream->Read( receivedData, 0, receivedData->Length );
      }

      bufferedTime = (DateTime::Now - startTime).TotalSeconds;
      Console::WriteLine( "{0} bytes received in {1} seconds.\n", bytesReceived.ToString(), bufferedTime.ToString(  "F1" ) );
      
      // Print the ratio of read times.
      Console::WriteLine( "Receiving data using the buffered "
      "network stream was {0} {1} than using the network "
      "stream alone.", (networkTime / bufferedTime).ToString(  "P0" ), bufferedTime < networkTime ? (String^)"faster" : "slower" );
   }

   static void SendData( Stream^ netStream, Stream^ bufStream )
   {
      DateTime startTime;
      Double networkTime;
      Double bufferedTime;
      
      // Create random data to send to the server.
      array<Byte>^dataToSend = gcnew array<Byte>(dataArraySize);
      (gcnew Random)->NextBytes( dataToSend );
      
      // Send the data using the NetworkStream.
      Console::WriteLine( "Sending data using NetworkStream." );
      startTime = DateTime::Now;
      for ( int i = 0; i < numberOfLoops; i++ )
      {
         netStream->Write( dataToSend, 0, dataToSend->Length );

      }
      networkTime = (DateTime::Now - startTime).TotalSeconds;
      Console::WriteLine( "{0} bytes sent in {1} seconds.\n", (numberOfLoops * dataToSend->Length).ToString(), networkTime.ToString(  "F1" ) );
      
      // Send the data using the BufferedStream.
      Console::WriteLine( "Sending data using BufferedStream." );
      startTime = DateTime::Now;
      for ( int i = 0; i < numberOfLoops; i++ )
      {
         bufStream->Write( dataToSend, 0, dataToSend->Length );

      }
      bufStream->Flush();
      bufferedTime = (DateTime::Now - startTime).TotalSeconds;
      Console::WriteLine( "{0} bytes sent in {1} seconds.\n", (numberOfLoops * dataToSend->Length).ToString(), bufferedTime.ToString(  "F1" ) );
      
      // Print the ratio of write times.
      Console::WriteLine( "Sending data using the buffered "
      "network stream was {0} {1} than using the network "
      "stream alone.\n", (networkTime / bufferedTime).ToString(  "P0" ), bufferedTime < networkTime ? (String^)"faster" : "slower" );
   }

};

int main( int argc, char *argv[] )
{
   
   // Check that an argument was specified when the 
   // program was invoked.
   if ( argc == 1 )
   {
      Console::WriteLine( "Error: The name of the host computer"
      " must be specified when the program is invoked." );
      return  -1;
   }

   String^ remoteName = gcnew String( argv[ 1 ] );
   
   // Create the underlying socket and connect to the server.
   Socket^ clientSocket = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   clientSocket->Connect( gcnew IPEndPoint( Dns::Resolve( remoteName )->AddressList[ 0 ],1800 ) );
   Console::WriteLine(  "Client is connected.\n" );
   
   // Create a NetworkStream that owns clientSocket and 
   // then create a BufferedStream on top of the NetworkStream.
   NetworkStream^ netStream = gcnew NetworkStream( clientSocket,true );
   BufferedStream^ bufStream = gcnew BufferedStream( netStream,streamBufferSize );
   
   try
   {
      
      // Check whether the underlying stream supports seeking.
      Console::WriteLine( "NetworkStream {0} seeking.\n", bufStream->CanSeek ? (String^)"supports" : "does not support" );
      
      // Send and receive data.
      if ( bufStream->CanWrite )
      {
         Client::SendData( netStream, bufStream );
      }
      
      if ( bufStream->CanRead )
      {
         Client::ReceiveData( netStream, bufStream );
      }
      
   }
   finally
   {
      
      // When bufStream is closed, netStream is in turn closed,
      // which in turn shuts down the connection and closes
      // clientSocket.
      Console::WriteLine( "\nShutting down connection." );
      bufStream->Close();
      
   }

}

using System;
using System.IO;
using System.Globalization;
using System.Net;
using System.Net.Sockets;

public class Client
{
    const int dataArraySize    =   100;
    const int streamBufferSize =  1000;
    const int numberOfLoops    = 10000;

    static void Main(string[] args)
    {
        // Check that an argument was specified when the
        // program was invoked.
        if(args.Length == 0)
        {
            Console.WriteLine("Error: The name of the host computer" +
                " must be specified when the program is invoked.");
            return;
        }

        string remoteName = args[0];

        // Create the underlying socket and connect to the server.
        Socket clientSocket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        clientSocket.Connect(new IPEndPoint(
            Dns.Resolve(remoteName).AddressList[0], 1800));

        Console.WriteLine("Client is connected.\n");

        // Create a NetworkStream that owns clientSocket and
        // then create a BufferedStream on top of the NetworkStream.
        // Both streams are disposed when execution exits the
        // using statement.
        using(Stream
            netStream = new NetworkStream(clientSocket, true),
            bufStream =
                  new BufferedStream(netStream, streamBufferSize))
        {
            // Check whether the underlying stream supports seeking.
            Console.WriteLine("NetworkStream {0} seeking.\n",
                bufStream.CanSeek ? "supports" : "does not support");

            // Send and receive data.
            if(bufStream.CanWrite)
            {
                SendData(netStream, bufStream);
            }
            if(bufStream.CanRead)
            {
                ReceiveData(netStream, bufStream);
            }

            // When bufStream is closed, netStream is in turn
            // closed, which in turn shuts down the connection
            // and closes clientSocket.
            Console.WriteLine("\nShutting down the connection.");
            bufStream.Close();
        }
    }

    static void SendData(Stream netStream, Stream bufStream)
    {
        DateTime startTime;
        double networkTime, bufferedTime;

        // Create random data to send to the server.
        byte[] dataToSend = new byte[dataArraySize];
        new Random().NextBytes(dataToSend);

        // Send the data using the NetworkStream.
        Console.WriteLine("Sending data using NetworkStream.");
        startTime = DateTime.Now;
        for(int i = 0; i < numberOfLoops; i++)
        {
            netStream.Write(dataToSend, 0, dataToSend.Length);
        }
        networkTime = (DateTime.Now - startTime).TotalSeconds;
        Console.WriteLine("{0} bytes sent in {1} seconds.\n",
            numberOfLoops * dataToSend.Length,
            networkTime.ToString("F1"));

        // Send the data using the BufferedStream.
        Console.WriteLine("Sending data using BufferedStream.");
        startTime = DateTime.Now;
        for(int i = 0; i < numberOfLoops; i++)
        {
            bufStream.Write(dataToSend, 0, dataToSend.Length);
        }
        bufStream.Flush();
        bufferedTime = (DateTime.Now - startTime).TotalSeconds;
        Console.WriteLine("{0} bytes sent in {1} seconds.\n",
            numberOfLoops * dataToSend.Length,
            bufferedTime.ToString("F1"));

        // Print the ratio of write times.
        Console.WriteLine("Sending data using the buffered " +
            "network stream was {0} {1} than using the network " +
            "stream alone.\n",
            (networkTime/bufferedTime).ToString("P0"),
            bufferedTime < networkTime ? "faster" : "slower");
    }

    static void ReceiveData(Stream netStream, Stream bufStream)
    {
        DateTime startTime;
        double networkTime, bufferedTime = 0;
        int bytesReceived = 0;
        byte[] receivedData = new byte[dataArraySize];

        // Receive data using the NetworkStream.
        Console.WriteLine("Receiving data using NetworkStream.");
        startTime = DateTime.Now;
        while(bytesReceived < numberOfLoops * receivedData.Length)
        {
            bytesReceived += netStream.Read(
                receivedData, 0, receivedData.Length);
        }
        networkTime = (DateTime.Now - startTime).TotalSeconds;
        Console.WriteLine("{0} bytes received in {1} seconds.\n",
            bytesReceived.ToString(),
            networkTime.ToString("F1"));

        // Receive data using the BufferedStream.
        Console.WriteLine("Receiving data using BufferedStream.");
        bytesReceived = 0;
        startTime = DateTime.Now;

        int numBytesToRead = receivedData.Length;

        while (numBytesToRead > 0)
        {
            // Read may return anything from 0 to numBytesToRead.
            int n = bufStream.Read(receivedData,0, receivedData.Length);
            // The end of the file is reached.
            if (n == 0)
                break;
            bytesReceived += n;
            numBytesToRead -= n;
        }

        bufferedTime = (DateTime.Now - startTime).TotalSeconds;
        Console.WriteLine("{0} bytes received in {1} seconds.\n",
            bytesReceived.ToString(),
            bufferedTime.ToString("F1"));

        // Print the ratio of read times.
        Console.WriteLine("Receiving data using the buffered network" +
            " stream was {0} {1} than using the network stream alone.",
            (networkTime/bufferedTime).ToString("P0"),
            bufferedTime < networkTime ? "faster" : "slower");
    }
}
' Compile using /r:System.dll.
Imports System.IO
Imports System.Globalization
Imports System.Net
Imports System.Net.Sockets

Public Class Client 

    Const dataArraySize As Integer    =   100
    Const streamBufferSize As Integer =  1000
    Const numberOfLoops As Integer    = 10000

    Shared Sub Main(args As String()) 
    
        ' Check that an argument was specified when the 
        ' program was invoked.
        If args.Length = 0 Then
            Console.WriteLine("Error: The name of the host " & _
                "computer must be specified when the program " & _ 
                "is invoked.")
            Return
        End If

        Dim remoteName As String = args(0)

        ' Create the underlying socket and connect to the server.
        Dim clientSocket As New Socket(AddressFamily.InterNetwork, _
            SocketType.Stream, ProtocolType.Tcp)

        clientSocket.Connect(New IPEndPoint( _
            Dns.Resolve(remoteName).AddressList(0), 1800))

        Console.WriteLine("Client is connected." & vbCrLf)

        ' Create a NetworkStream that owns clientSocket and then 
        ' create a BufferedStream on top of the NetworkStream.
        Dim netStream As New NetworkStream(clientSocket, True)
        Dim bufStream As New _
            BufferedStream(netStream, streamBufferSize)
        
        Try
            ' Check whether the underlying stream supports seeking.
            If bufStream.CanSeek Then
                Console.WriteLine("NetworkStream supports" & _
                    "seeking." & vbCrLf)
            Else
                Console.WriteLine("NetworkStream does not " & _
                    "support seeking." & vbCrLf)
            End If

            ' Send and receive data.
            If bufStream.CanWrite Then
                SendData(netStream, bufStream)
            End If            
            If bufStream.CanRead Then
                ReceiveData(netStream, bufStream)
            End If
        Finally

            ' When bufStream is closed, netStream is in turn 
            ' closed, which in turn shuts down the connection 
            ' and closes clientSocket.
            Console.WriteLine(vbCrLf & "Shutting down the connection.")
            bufStream.Close()
        End Try
    End Sub

    Shared Sub SendData(netStream As Stream, bufStream As Stream)
    
        Dim startTime As DateTime 
        Dim networkTime As Double, bufferedTime As Double 

        ' Create random data to send to the server.
        Dim dataToSend(dataArraySize - 1) As Byte
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(dataToSend)

        ' Send the data using the NetworkStream.
        Console.WriteLine("Sending data using NetworkStream.")
        startTime = DateTime.Now
        For i As Integer = 1 To numberOfLoops
            netStream.Write(dataToSend, 0, dataToSend.Length)
        Next i
        networkTime = DateTime.Now.Subtract(startTime).TotalSeconds
        Console.WriteLine("{0} bytes sent in {1} seconds." & vbCrLf, _
            numberOfLoops * dataToSend.Length, _
            networkTime.ToString("F1"))

        ' Send the data using the BufferedStream.
        Console.WriteLine("Sending data using BufferedStream.")
        startTime = DateTime.Now
        For i As Integer = 1 To numberOfLoops
            bufStream.Write(dataToSend, 0, dataToSend.Length)
        Next i
        
        bufStream.Flush()
        bufferedTime = DateTime.Now.Subtract(startTime).TotalSeconds
        Console.WriteLine("{0} bytes sent In {1} seconds." & vbCrLf, _
            numberOfLoops * dataToSend.Length, _
            bufferedTime.ToString("F1"))

        ' Print the ratio of write times.
        Console.Write("Sending data using the buffered " & _
            "network stream was {0}", _
            (networkTime/bufferedTime).ToString("P0"))
        If bufferedTime < networkTime Then
            Console.Write(" faster")
        Else
            Console.Write(" slower")
        End If
        Console.WriteLine(" than using the network stream alone.")
    End Sub

    Shared Sub ReceiveData(netStream As Stream, bufStream As Stream)
    
        Dim startTime As DateTime 
        Dim networkTime As Double, bufferedTime As Double = 0

        Dim bytesReceived As Integer = 0
        Dim receivedData(dataArraySize - 1) As Byte

        ' Receive data using the NetworkStream.
        Console.WriteLine("Receiving data using NetworkStream.")
        startTime = DateTime.Now
        While bytesReceived < numberOfLoops * receivedData.Length
            bytesReceived += netStream.Read( _
                receivedData, 0, receivedData.Length)
        End While
        networkTime = DateTime.Now.Subtract(startTime).TotalSeconds
        Console.WriteLine("{0} bytes received in {1} " & _
            "seconds." & vbCrLf, _
            bytesReceived.ToString(), _
            networkTime.ToString("F1"))

        ' Receive data using the BufferedStream.
        Console.WriteLine("Receiving data using BufferedStream.")
        bytesReceived = 0
        startTime = DateTime.Now

        Dim numBytesToRead As Integer = receivedData.Length
        Dim n As Integer
        Do While numBytesToRead > 0

            'Read my return anything from 0 to numBytesToRead
            n = bufStream.Read(receivedData, 0, receivedData.Length)
            'The end of the file is reached.
            If n = 0 Then
                Exit Do
            End If

            bytesReceived += n
            numBytesToRead -= n
        Loop

        bufferedTime = DateTime.Now.Subtract(startTime).TotalSeconds
        Console.WriteLine("{0} bytes received in {1} " & _
            "seconds." & vbCrLf, _
            bytesReceived.ToString(), _
            bufferedTime.ToString("F1"))

        ' Print the ratio of read times.
        Console.Write("Receiving data using the buffered " & _
            "network stream was {0}", _
            (networkTime/bufferedTime).ToString("P0"))
        If bufferedTime < networkTime Then
            Console.Write(" faster")
        Else
            Console.Write(" slower")
        End If
        Console.WriteLine(" than using the network stream alone.")
    End Sub
End Class

예제 2: 서버에서 실행 되는 코드Example 2: Code that runs on the server

#using <system.dll>

using namespace System;
using namespace System::Net;
using namespace System::Net::Sockets;
int main()
{
   
   // This is a Windows Sockets 2 error code.
   const int WSAETIMEDOUT = 10060;
   Socket^ serverSocket;
   int bytesReceived;
   int totalReceived = 0;
   array<Byte>^receivedData = gcnew array<Byte>(2000000);
   
   // Create random data to send to the client.
   array<Byte>^dataToSend = gcnew array<Byte>(2000000);
   (gcnew Random)->NextBytes( dataToSend );
   IPAddress^ ipAddress = Dns::Resolve( Dns::GetHostName() )->AddressList[ 0 ];
   IPEndPoint^ ipEndpoint = gcnew IPEndPoint( ipAddress,1800 );
   
   // Create a socket and listen for incoming connections.
   Socket^ listenSocket = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   try
   {
      listenSocket->Bind( ipEndpoint );
      listenSocket->Listen( 1 );
      
      // Accept a connection and create a socket to handle it.
      serverSocket = listenSocket->Accept();
      Console::WriteLine( "Server is connected.\n" );
   }
   finally
   {
      listenSocket->Close();
   }

   try
   {
      
      // Send data to the client.
      Console::Write( "Sending data ... " );
      int bytesSent = serverSocket->Send( dataToSend, 0, dataToSend->Length, SocketFlags::None );
      Console::WriteLine( "{0} bytes sent.\n", bytesSent.ToString() );
      
      // Set the timeout for receiving data to 2 seconds.
      serverSocket->SetSocketOption( SocketOptionLevel::Socket, SocketOptionName::ReceiveTimeout, 2000 );
      
      // Receive data from the client.
      Console::Write( "Receiving data ... " );
      try
      {
         do
         {
            bytesReceived = serverSocket->Receive( receivedData, 0, receivedData->Length, SocketFlags::None );
            totalReceived += bytesReceived;
         }
         while ( bytesReceived != 0 );
      }
      catch ( SocketException^ e ) 
      {
         if ( e->ErrorCode == WSAETIMEDOUT )
         {
            
            // Data was not received within the given time.
            // Assume that the transmission has ended.
         }
         else
         {
            Console::WriteLine( "{0}: {1}\n", e->GetType()->Name, e->Message );
         }
      }
      finally
      {
         Console::WriteLine( "{0} bytes received.\n", totalReceived.ToString() );
      }

   }
   finally
   {
      serverSocket->Shutdown( SocketShutdown::Both );
      Console::WriteLine( "Connection shut down." );
      serverSocket->Close();
   }

}

using System;
using System.Net;
using System.Net.Sockets;

public class Server 
{
    static void Main() 
    {
        // This is a Windows Sockets 2 error code.
        const int WSAETIMEDOUT = 10060;

        Socket serverSocket;
        int bytesReceived, totalReceived = 0;
        byte[] receivedData = new byte[2000000];

        // Create random data to send to the client.
        byte[] dataToSend = new byte[2000000];
        new Random().NextBytes(dataToSend);

        IPAddress ipAddress =
            Dns.Resolve(Dns.GetHostName()).AddressList[0];

        IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 1800);

        // Create a socket and listen for incoming connections.
        using(Socket listenSocket = new Socket(
            AddressFamily.InterNetwork, SocketType.Stream, 
            ProtocolType.Tcp))
        {
            listenSocket.Bind(ipEndpoint);
            listenSocket.Listen(1);

            // Accept a connection and create a socket to handle it.
            serverSocket = listenSocket.Accept();
            Console.WriteLine("Server is connected.\n");
        }

        try
        {
            // Send data to the client.
            Console.Write("Sending data ... ");
            int bytesSent = serverSocket.Send(
                dataToSend, 0, dataToSend.Length, SocketFlags.None);
            Console.WriteLine("{0} bytes sent.\n", 
                bytesSent.ToString());

            // Set the timeout for receiving data to 2 seconds.
            serverSocket.SetSocketOption(SocketOptionLevel.Socket,
                SocketOptionName.ReceiveTimeout, 2000);

            // Receive data from the client.
            Console.Write("Receiving data ... ");
            try
            {
                do
                {
                    bytesReceived = serverSocket.Receive(receivedData,
                        0, receivedData.Length, SocketFlags.None);
                    totalReceived += bytesReceived;
                }
                while(bytesReceived != 0);
            }
            catch(SocketException e)
            {
                if(e.ErrorCode == WSAETIMEDOUT)
                {
                    // Data was not received within the given time.
                    // Assume that the transmission has ended.
                }
                else
                {
                    Console.WriteLine("{0}: {1}\n", 
                        e.GetType().Name, e.Message);
                }
            }
            finally
            {
                Console.WriteLine("{0} bytes received.\n",
                    totalReceived.ToString());
            }
        }
        finally
        {
            serverSocket.Shutdown(SocketShutdown.Both);
            Console.WriteLine("Connection shut down.");
            serverSocket.Close();
        }
    }
}
' Compile using /r:System.dll.
Imports System.Net
Imports System.Net.Sockets

Public Class Server 

    Shared Sub Main() 
    
        ' This is a Windows Sockets 2 error code.
        Const WSAETIMEDOUT As Integer = 10060

        Dim serverSocket As Socket 
        Dim bytesReceived As Integer
        Dim totalReceived As Integer = 0
        Dim receivedData(2000000-1) As Byte

        ' Create random data to send to the client.
        Dim dataToSend(2000000-1) As Byte
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(dataToSend)

        Dim ipAddress As IPAddress = _
            Dns.Resolve(Dns.GetHostName()).AddressList(0)

        Dim ipEndpoint As New IPEndPoint(ipAddress, 1800)

        ' Create a socket and listen for incoming connections.
        Dim listenSocket As New Socket(AddressFamily.InterNetwork, _
            SocketType.Stream, ProtocolType.Tcp)
        
        Try
            listenSocket.Bind(ipEndpoint)
            listenSocket.Listen(1)

            ' Accept a connection and create a socket to handle it.
            serverSocket = listenSocket.Accept()
            Console.WriteLine("Server is connected." & vbCrLf)
        Finally
            listenSocket.Close()
        End Try

        Try
            ' Send data to the client.
            Console.Write("Sending data ... ")
            Dim bytesSent As Integer = serverSocket.Send( _
                dataToSend, 0, dataToSend.Length, SocketFlags.None)
            Console.WriteLine("{0} bytes sent." & vbCrLf, _
                bytesSent.ToString())

            ' Set the timeout for receiving data to 2 seconds.
            serverSocket.SetSocketOption(SocketOptionLevel.Socket, _
                SocketOptionName.ReceiveTimeout, 2000)

            ' Receive data from the client.
            Console.Write("Receiving data ... ")
            Try
                Do
                    bytesReceived = serverSocket.Receive( _
                        receivedData, 0, receivedData.Length, _
                        SocketFlags.None)
                    totalReceived += bytesReceived
                Loop While bytesReceived <> 0
            Catch e As SocketException
                If(e.ErrorCode = WSAETIMEDOUT)
                
                    ' Data was not received within the given time.
                    ' Assume that the transmission has ended.
                Else
                    Console.WriteLine("{0}: {1}" & vbCrLf, _
                        e.GetType().Name, e.Message)
                End If
            Finally
                Console.WriteLine("{0} bytes received." & vbCrLf, _
                    totalReceived.ToString())
            End Try
        Finally
            serverSocket.Shutdown(SocketShutdown.Both)
            Console.WriteLine("Connection shut down.")
            serverSocket.Close()
        End Try
    
    End Sub
End Class

설명

버퍼는 운영 체제에 대 한 호출의 수를 줄이는 하는 데이터를 캐시 하는 데 사용 되는 메모리의 바이트 블록.A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. 버퍼 개선 읽기 및 쓰기 성능을 합니다.Buffers improve read and write performance. 버퍼 읽기 또는 쓰기, 하지만에 되지 둘 다 동시에 사용할 수 있습니다.A buffer can be used for either reading or writing, but never both simultaneously. BufferedStreamReadWrite 메서드는 자동으로 버퍼를 유지 관리 합니다.The Read and Write methods of BufferedStream automatically maintain the buffer.

중요

이 형식이 구현 하는 IDisposable 인터페이스입니다.This type implements the IDisposable interface. 형식을 사용 하 여 마쳤으면 직접 또는 간접적으로의 삭제 해야 있습니다.When you have finished using the type, you should dispose of it either directly or indirectly. 직접 형식의 dispose 호출 해당 Dispose 의 메서드를 try / catch 블록입니다.To dispose of the type directly, call its Dispose method in a try/catch block. 삭제 하지 직접, 언어 구문 같은 사용 using (C#에서) 또는 Using (Visual Basic에서는).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 자세한 내용은 "를 사용 하는 개체는 구현 IDisposable" 섹션을 참조 하세요.를 IDisposable 인터페이스 항목입니다.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

BufferedStream는 특정 유형의 스트림을 기반으로 구성할 수 있습니다.BufferedStream can be composed around certain types of streams. 바이트 읽기 및 쓰기는 기본 데이터 소스 또는 리포지토리에 대 한 구현을 제공 합니다.It provides implementations for reading and writing bytes to an underlying data source or repository. 다른 데이터 형식을 읽고 쓰려면 BinaryReaderBinaryWriter를 사용 합니다.Use BinaryReader and BinaryWriter for reading and writing other data types. BufferedStream는 버퍼가 필요 하지 않을 때 버퍼의 입력 및 출력 속도가 저하 되는 것을 방지 하도록 디자인 되었습니다.BufferedStream is designed to prevent the buffer from slowing down input and output when the buffer is not needed. 내부 버퍼 크기 보다 큰 크기에 대해 항상 읽고 쓰려면 BufferedStream 내부 버퍼를 할당 하지 않을 수 있습니다.If you always read and write for sizes greater than the internal buffer size, then BufferedStream might not even allocate the internal buffer. 또한 BufferedStream은 공유 버퍼에서 읽기와 쓰기를 버퍼링 합니다.BufferedStream also buffers reads and writes in a shared buffer. 거의 항상 일련의 읽기 또는 쓰기를 수행할 수는 있지만 둘 사이 번갈아 전환 거의 간주 됩니다.It is assumed that you will almost always be doing a series of reads or writes, but rarely alternate between the two of them.

생성자

BufferedStream(Stream)

기본 버퍼 크기인 4096바이트를 사용하여 BufferedStream 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the BufferedStream class with a default buffer size of 4096 bytes.

BufferedStream(Stream, Int32)

지정된 버퍼 크기를 사용하여 BufferedStream 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the BufferedStream class with the specified buffer size.

속성

BufferSize

이 버퍼링된 스트림의 버퍼 크기(바이트)를 가져옵니다.Gets the buffer size in bytes for this buffered stream.

CanRead

현재 스트림이 읽기를 지원하는지를 나타내는 값을 가져옵니다.Gets a value indicating whether the current stream supports reading.

CanSeek

현재 스트림이 검색을 지원하는지를 나타내는 값을 가져옵니다.Gets a value indicating whether the current stream supports seeking.

CanTimeout

현재 스트림이 시간 초과될 수 있는지를 결정하는 값을 가져옵니다.Gets a value that determines whether the current stream can time out.

(다음에서 상속됨 Stream)
CanWrite

현재 스트림이 쓰기를 지원하는지를 나타내는 값을 가져옵니다.Gets a value indicating whether the current stream supports writing.

Length

스트림 길이(바이트)를 가져옵니다.Gets the stream length in bytes.

Position

현재 스트림 내에서의 위치를 가져옵니다.Gets the position within the current stream.

ReadTimeout

스트림 읽기 시도가 만료되기 전까지 기다릴 시간을 결정하는 값(밀리초)을 가져오거나 설정합니다.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(다음에서 상속됨 Stream)
UnderlyingStream

이 버퍼링된 스트림의 내부 Stream 인스턴스를 가져옵니다.Gets the underlying Stream instance for this buffered stream.

WriteTimeout

스트림 쓰기 시도가 만료되기 전까지 기다릴 시간을 결정하는 값(밀리초)을 가져오거나 설정합니다.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(다음에서 상속됨 Stream)

메서드

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

비동기 읽기 작업을 시작합니다.Begins an asynchronous read operation. 대신 ReadAsync(Byte[], Int32, Int32, CancellationToken)를 사용하세요.(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

비동기 쓰기 작업을 시작합니다.Begins an asynchronous write operation. 대신 WriteAsync(Byte[], Int32, Int32, CancellationToken)를 사용하세요.(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Close()

스트림을 닫고 현재 버퍼링된 스트림과 관련된 리소스(특히 소켓 및 파일 핸들과 같은 시스템 리스소)를 해제합니다.Closes the stream and releases any resources (especially system resources such as sockets and file handles) associated with the current buffered stream.

CopyTo(Stream)

현재 스트림에서 바이트를 읽어서 다른 스트림에 해당 바이트를 씁니다.Reads the bytes from the current stream and writes them to another stream.

(다음에서 상속됨 Stream)
CopyTo(Stream, Int32)

현재 버퍼링된 스트림에서 바이트를 읽어서 다른 스트림에 해당 바이트를 씁니다.Reads the bytes from the current buffered stream and writes them to another stream.

CopyToAsync(Stream)

현재 스트림에서 모든 바이트를 비동기적으로 읽어 다른 스트림에 씁니다.Asynchronously reads the bytes from the current stream and writes them to another stream.

(다음에서 상속됨 Stream)
CopyToAsync(Stream, CancellationToken)

현재 스트림에서 바이트를 비동기적으로 읽어 지정된 취소 토큰을 사용하여 다른 스트림에 씁니다.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(다음에서 상속됨 Stream)
CopyToAsync(Stream, Int32)

현재 스트림에서 바이트를 비동기적으로 읽어 지정된 버퍼 크기로 다른 스트림에 씁니다.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(다음에서 상속됨 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

현재 버퍼링된 스트림에서 바이트를 비동기적으로 읽어 지정된 버퍼 크기 및 취소 토큰을 사용하여 다른 스트림에 씁니다.Asynchronously reads the bytes from the current buffered stream and writes them to another stream, using a specified buffer size and cancellation token.

CreateObjRef(Type)

원격 개체와 통신 하는 데 프록시를 생성 하는 데 필요한 모든 관련 정보를 포함 하는 개체를 만듭니다.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(다음에서 상속됨 MarshalByRefObject)
CreateWaitHandle()

WaitHandle 개체를 할당합니다.Allocates a WaitHandle object.

(다음에서 상속됨 Stream)
Dispose()

Stream에서 사용하는 모든 리소스를 해제합니다.Releases all resources used by the Stream.

(다음에서 상속됨 Stream)
Dispose(Boolean)

Stream에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다.Releases the unmanaged resources used by the Stream and optionally releases the managed resources.

(다음에서 상속됨 Stream)
DisposeAsync()

버퍼링된 스트림에서 사용하는 비관리형 리소스를 비동기적으로 해제합니다.Asynchronously releases the unmanaged resources used by the buffered stream.

EndRead(IAsyncResult)

보류 중인 비동기 읽기 작업이 완료되기를 기다립니다.Waits for the pending asynchronous read operation to complete. 대신 ReadAsync(Byte[], Int32, Int32, CancellationToken)를 사용하세요.(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

EndWrite(IAsyncResult)

비동기 쓰기 작업을 종료하고 I/O 작업이 완료될 때까지 차단시킵니다.Ends an asynchronous write operation and blocks until the I/O operation is complete. 대신 WriteAsync(Byte[], Int32, Int32, CancellationToken)를 사용하세요.(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Equals(Object)

지정한 개체가 현재 개체와 같은지를 확인합니다.Determines whether the specified object is equal to the current object.

(다음에서 상속됨 Object)
Flush()

이 스트림에 대한 모든 버퍼를 지우고 버퍼링된 모든 데이터가 내부 디바이스에 쓰여지도록 합니다.Clears all buffers for this stream and causes any buffered data to be written to the underlying device.

FlushAsync()

이 스트림에 대한 모든 버퍼를 비동기적으로 지우고 버퍼링된 모든 데이터가 내부 디바이스에 비동기적으로 쓰여지도록 합니다.Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(다음에서 상속됨 Stream)
FlushAsync(CancellationToken)

이 스트림에 대해 모든 버퍼를 비동기적으로 지우고 버퍼링된 데이터가 내부 디바이스에 쓰여지도록 하고 취소 요청을 모니터링합니다.Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

GetHashCode()

기본 해시 함수로 작동합니다.Serves as the default hash function.

(다음에서 상속됨 Object)
GetLifetimeService()

이 인스턴스의 수명 정책을 제어 하는 현재의 수명 서비스 개체를 검색 합니다.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(다음에서 상속됨 MarshalByRefObject)
GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(다음에서 상속됨 Object)
InitializeLifetimeService()

이 인스턴스의 수명 정책을 제어하는 수명 서비스 개체를 가져옵니다.Obtains a lifetime service object to control the lifetime policy for this instance.

(다음에서 상속됨 MarshalByRefObject)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(다음에서 상속됨 Object)
MemberwiseClone(Boolean)

현재 MarshalByRefObject 개체의 단순 복사본을 만듭니다.Creates a shallow copy of the current MarshalByRefObject object.

(다음에서 상속됨 MarshalByRefObject)
ObjectInvariant()

Contract에 대한 지원을 제공합니다.Provides support for a Contract.

(다음에서 상속됨 Stream)
Read(Byte[], Int32, Int32)

현재 버퍼링된 스트림의 바이트를 배열에 복사합니다.Copies bytes from the current buffered stream to an array.

Read(Span<Byte>)

현재 버퍼링된 스트림에서 바이트 범위로 바이트를 복사하고 버퍼링된 스트림 내에서의 위치를 쓴 바이트 수만큼 이동합니다.Copies bytes from the current buffered stream to a byte span and advances the position within the buffered stream by the number of bytes read.

ReadAsync(Byte[], Int32, Int32)

현재 스트림에서 바이트 시퀀스를 읽고 읽은 바이트 수만큼 스트림에서 위치를 비동기적으로 앞으로 이동합니다.Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(다음에서 상속됨 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

현재 스트림에서 바이트의 시퀀스를 비동기적으로 읽고 읽은 바이트 수만큼 스트림 내에서 앞으로 이동하며 취소 요청을 모니터링합니다.Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken)

현재 버퍼링된 스트림에서 바이트 시퀀스를 읽고 읽은 바이트 수만큼 버퍼링된 스트림에서 위치를 비동기적으로 앞으로 이동합니다.Asynchronously reads a sequence of bytes from the current buffered stream and advances the position within the buffered stream by the number of bytes read.

ReadByte()

원본 스트림에서 바이트를 읽고 int로 캐스팅된 바이트를 반환하거나 스트림의 끝에서 읽는 경우 -1을 반환합니다.Reads a byte from the underlying stream and returns the byte cast to an int, or returns -1 if reading from the end of the stream.

Seek(Int64, SeekOrigin)

버퍼링된 현재 스트림 내에서의 위치를 설정합니다.Sets the position within the current buffered stream.

SetLength(Int64)

버퍼링된 스트림의 길이를 설정합니다.Sets the length of the buffered stream.

ToString()

현재 개체를 나타내는 string을 반환합니다.Returns a string that represents the current object.

(다음에서 상속됨 Object)
Write(Byte[], Int32, Int32)

버퍼링된 스트림에 바이트를 복사하고 버퍼링된 스트림 내에서의 현재 위치를 쓴 바이트 수만큼 이동합니다.Copies bytes to the buffered stream and advances the current position within the buffered stream by the number of bytes written.

Write(ReadOnlySpan<Byte>)

현재 버퍼링된 스트림에 바이트 시퀀스를 쓰고 쓴 바이트 수만큼 이 버퍼링된 스트림에서 현재 위치를 앞으로 이동합니다.Writes a sequence of bytes to the current buffered stream and advances the current position within this buffered stream by the number of bytes written.

WriteAsync(Byte[], Int32, Int32)

현재 스트림에 바이트 시퀀스를 비동기적으로 쓰고 쓴 바이트 수만큼 이 스트림에서 현재 위치를 앞으로 이동합니다.Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(다음에서 상속됨 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

바이트의 시퀀스를 현재 스트림에 비동기적으로 쓰고 쓰여진 바이트 수만큼 이 스트림 내의 현재 위치를 앞으로 이동한 후 취소 요청을 모니터링합니다.Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

바이트의 시퀀스를 현재 버퍼링된 스트림에 비동기적으로 쓰고 쓰여진 바이트 수만큼 이 버퍼링된 스트림 내의 현재 위치를 앞으로 이동한 후 취소 요청을 모니터링합니다.Asynchronously writes a sequence of bytes to the current buffered stream, advances the current position within this buffered stream by the number of bytes written, and monitors cancellation requests.

WriteByte(Byte)

버퍼링된 스트림의 현재 위치에 바이트를 씁니다.Writes a byte to the current position in the buffered stream.

명시적 인터페이스 구현

IDisposable.Dispose()

Stream에서 사용하는 모든 리소스를 해제합니다.Releases all resources used by the Stream.

(다음에서 상속됨 Stream)

적용 대상

추가 정보