BufferedStream BufferedStream BufferedStream BufferedStream Class

Definition

Fügt eine Pufferungsschicht für Lese- und Schreibvorgänge in einem anderen Stream hinzu.Adds a buffering layer to read and write operations on another stream. Diese Klasse kann nicht vererbt werden.This class cannot be inherited.

public ref class BufferedStream sealed : 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
Vererbung
Attribute

Beispiele

In den folgenden Codebeispielen wird gezeigt, wie BufferedStream die-Klasse NetworkStream für die-Klasse verwendet wird, um die Leistung bestimmter e/a-Vorgänge zu erhöhen.The following code examples show how to use the BufferedStream class over the NetworkStream class to increase the performance of certain I/O operations. Starten Sie den Server auf einem Remote Computer, bevor Sie den Client starten.Start the server on a remote computer before starting the client. Geben Sie den Remote Computernamen als Befehlszeilenargument an, wenn Sie den Client starten.Specify the remote computer name as a command-line argument when starting the client. Variieren Sie dataArraySize die streamBufferSize Konstanten und, um ihre Auswirkungen auf die Leistung anzuzeigen.Vary the dataArraySize and streamBufferSize constants to view their effect on performance.

Das erste Beispiel zeigt den Code, der auf dem Client ausgeführt wird, und das zweite Beispiel zeigt den Code, der auf dem Server ausgeführt wird.The first example shows the code that runs on the client, and the second example shows the code that runs on the server.

Beispiel 1: Code, der auf dem Client ausgeführt wirdExample 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 Microsoft.VisualBasic
Imports System
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

Beispiel 2: Code, der auf dem Server ausgeführt wirdExample 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 Microsoft.VisualBasic
Imports System
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

Hinweise

Ein Puffer ist ein Block von Bytes im Arbeitsspeicher, der zum Zwischenspeichern von Daten verwendet wird. Dadurch wird die Anzahl der Aufrufe des Betriebssystems reduziert.A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. Puffer verbessern die Lese-und Schreibleistung.Buffers improve read and write performance. Ein Puffer kann entweder für Lese-oder Schreibvorgänge verwendet werden, aber nicht beide gleichzeitig.A buffer can be used for either reading or writing, but never both simultaneously. Die-Methode und BufferedStream die- Write Methode von verwalten den Puffer automatisch. ReadThe Read and Write methods of BufferedStream automatically maintain the buffer.

Wichtig

Dieser Typ implementiert die IDisposable-Schnittstelle.This type implements the IDisposable interface. Nach Abschluss der Verwendung sollten Sie den Typ entweder direkt oder indirekt löschen.When you have finished using the type, you should dispose of it either directly or indirectly. Zum direkten Löschen des Typs rufen Sie seine Dispose-Methode in einem try/catch-Block auf.To dispose of the type directly, call its Dispose method in a try/catch block. Zum indirekten Löschen verwenden Sie ein Sprachkonstrukt wie using (in C#) oder Using (in Visual Basic).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Weitere Informationen finden Sie im Abschnitt „Verwenden eines Objekts, das IDisposable implementiert“ des Themas „Die IDisposable-Schnittstelle“.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

BufferedStreamkann für bestimmte Arten von Streams zusammengesetzt werden.BufferedStream can be composed around certain types of streams. Es stellt Implementierungen zum Lesen und Schreiben von Bytes in einer zugrunde liegenden Datenquelle oder einem zugrunde liegenden Repository bereit.It provides implementations for reading and writing bytes to an underlying data source or repository. Verwenden BinaryReader Sie BinaryWriter und zum Lesen und Schreiben anderer Datentypen.Use BinaryReader and BinaryWriter for reading and writing other data types. BufferedStreamwurde entworfen, um zu verhindern, dass der Puffer die Eingabe und Ausgabe verlangsamt, wenn der Puffer nicht benötigt wird.BufferedStream is designed to prevent the buffer from slowing down input and output when the buffer is not needed. Wenn Sie immer Lese-und Schreibvorgänge für Größen haben, die größer als die BufferedStream interne Puffergröße sind, wird der interne Puffer von möglicherweise nicht einmal von der KlasseIf you always read and write for sizes greater than the internal buffer size, then BufferedStream might not even allocate the internal buffer. BufferedStreampuffert auch Lese-und Schreibvorgänge in einem freigegebenen Puffer.BufferedStream also buffers reads and writes in a shared buffer. Es wird davon ausgegangen, dass Sie fast immer eine Reihe von Lese-oder Schreibvorgängen durchgehen, aber nur selten zwischen den beiden wechseln.It is assumed that you will almost always be doing a series of reads or writes, but rarely alternate between the two of them.

Konstruktoren

BufferedStream(Stream) BufferedStream(Stream) BufferedStream(Stream) BufferedStream(Stream)

Initialisiert eine neue Instanz der BufferedStream-Klasse mit einer Standardpuffergröße von 4096 Bytes.Initializes a new instance of the BufferedStream class with a default buffer size of 4096 bytes.

BufferedStream(Stream, Int32) BufferedStream(Stream, Int32) BufferedStream(Stream, Int32) BufferedStream(Stream, Int32)

Initialisiert eine neue Instanz der BufferedStream-Klasse mit der angegebenen Puffergröße.Initializes a new instance of the BufferedStream class with the specified buffer size.

Eigenschaften

BufferSize BufferSize BufferSize BufferSize

Ruft die Puffergröße in Bytes für diesen gepufferten Stream ab.Gets the buffer size in bytes for this buffered stream.

CanRead CanRead CanRead CanRead

Ruft einen Wert ab, der angibt, ob der aktuelle Stream Lesevorgänge unterstützt.Gets a value indicating whether the current stream supports reading.

CanSeek CanSeek CanSeek CanSeek

Ruft einen Wert ab, der angibt, ob der aktuelle Stream Suchvorgänge unterstützt.Gets a value indicating whether the current stream supports seeking.

CanTimeout CanTimeout CanTimeout CanTimeout

Ruft einen Wert ab, der bestimmt, ob für den aktuellen Stream ein Timeout möglich ist.Gets a value that determines whether the current stream can time out.

(Inherited from Stream)
CanWrite CanWrite CanWrite CanWrite

Ruft einen Wert ab, der angibt, ob der aktuelle Stream Schreibvorgänge unterstützt.Gets a value indicating whether the current stream supports writing.

Length Length Length Length

Ruft die Länge des Streams in Bytes ab.Gets the stream length in bytes.

Position Position Position Position

Ruft die Position im aktuellen Stream ab.Gets the position within the current stream.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

Ruft einen Wert in Millisekunden ab, der bestimmt, wie lange der Stream versucht, Lesevorgänge durchzuführen, bevor ein Timeout auftritt, oder legt diesen fest.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(Inherited from Stream)
UnderlyingStream UnderlyingStream UnderlyingStream UnderlyingStream

Ruft die zugrunde liegende Stream-Instanz für diesen gepufferten Stream ab.Gets the underlying Stream instance for this buffered stream.

WriteTimeout WriteTimeout WriteTimeout WriteTimeout

Ruft einen Wert in Millisekunden ab, der bestimmt, wie lange der Stream versucht, Schreibvorgänge durchzuführen, bevor ein Timeout auftritt, oder legt diesen fest.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(Inherited from Stream)

Methoden

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

Beginnt einen asynchronen Lesevorgang.Begins an asynchronous read operation. (Verwenden Sie stattdessen ReadAsync(Byte[], Int32, Int32, CancellationToken).)(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

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

Beginnt einen asynchronen Schreibvorgang.Begins an asynchronous write operation. (Verwenden Sie stattdessen WriteAsync(Byte[], Int32, Int32, CancellationToken).)(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Close() Close() Close() Close()

Schließt den Stream und gibt alle Ressourcen frei (insbesondere Systemressourcen wie Sockets und Dateihandles), die dem aktuellen Pufferstream zugeordnet sind.Closes the stream and releases any resources (especially system resources such as sockets and file handles) associated with the current buffered stream.

CopyTo(Stream) CopyTo(Stream) CopyTo(Stream) CopyTo(Stream)

Liest alle Bytes aus dem aktuellen Stream und schreibt sie in einen anderen Datenstrom.Reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32)

Liest alle Bytes aus dem aktuellen gepufferten Stream und schreibt sie in einen anderen Datenstrom.Reads the bytes from the current buffered stream and writes them to another stream.

CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream)

Liest die Bytes asynchron aus dem aktuellen Stream und schreibt sie in einen anderen Stream.Asynchronously reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken)

Liest die Bytes asynchron aus dem aktuellen Stream und schreibt sie unter Verwendung eines angegebenen Abbruchtokens in einen anderen Stream.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(Inherited from Stream)
CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32)

Liest die Bytes asynchron aus dem aktuellen Stream und schreibt sie unter Verwendung einer angegebenen Puffergröße in einen anderen Stream.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Inherited from Stream)
CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken)

Liest die Bytes asynchron aus dem aktuellen gepufferten Stream und schreibt sie unter Verwendung einer angegebenen Puffergröße und eines Abbruchtokens in einen anderen Stream.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) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Erstellt ein Objekt mit allen relevanten Informationen, die zum Generieren eines Proxys für die Kommunikation mit einem Remoteobjekt erforderlich sind.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateWaitHandle() CreateWaitHandle() CreateWaitHandle() CreateWaitHandle()

Reserviert ein WaitHandle-Objekt.Allocates a WaitHandle object.

(Inherited from Stream)
Dispose() Dispose() Dispose() Dispose()

Gibt alle vom Stream verwendeten Ressourcen frei.Releases all resources used by the Stream.

(Inherited from Stream)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Gibt die von Stream verwendeten nicht verwalteten Ressourcen und optional die verwalteten Ressourcen frei.Releases the unmanaged resources used by the Stream and optionally releases the managed resources.

(Inherited from Stream)
DisposeAsync() DisposeAsync() DisposeAsync() DisposeAsync()

Gibt die nicht verwalteten Ressourcen, die vom gepufferten Stream verwendet werden, asynchron frei.Asynchronously releases the unmanaged resources used by the buffered stream.

EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult)

Wartet, bis der ausstehende asynchrone Lesevorgang abgeschlossen ist.Waits for the pending asynchronous read operation to complete. (Verwenden Sie stattdessen ReadAsync(Byte[], Int32, Int32, CancellationToken).)(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult)

Beendet einen asynchronen Schreibvorgang und blockiert, bis die E/A-Operation abgeschlossen wurde.Ends an asynchronous write operation and blocks until the I/O operation is complete. (Verwenden Sie stattdessen WriteAsync(Byte[], Int32, Int32, CancellationToken).)(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Bestimmt, ob das angegebene Objekt mit dem aktuellen Objekt identisch ist.Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush() Flush() Flush() Flush()

Löscht sämtliche Puffer für diesen Stream und veranlasst die Ausgabe aller gepufferten Daten an das zugrunde liegende Gerät.Clears all buffers for this stream and causes any buffered data to be written to the underlying device.

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

Löscht sämtliche Puffer für diesen Stream asynchron und veranlasst die Ausgabe aller gepufferten Daten an das zugrunde liegende Gerät.Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Inherited from Stream)
FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken)

Löscht alle Puffer für diesen Stream asynchron und veranlasst die Ausgabe aller gepufferten Daten an das zugrunde liegende Gerät und überwacht Abbruchanforderungen.Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Fungiert als Standardhashfunktion.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Ruft das aktuelle Lebensdauerdienstobjekt ab, das die Lebensdauerrichtlinien für diese Instanz steuert.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

Ruft den Type der aktuellen Instanz ab.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Ruft ein Lebensdauerdienstobjekt zur Steuerung der Lebensdauerrichtlinie für diese Instanz ab.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Erstellt eine flache Kopie des aktuellen MarshalByRefObject-Objekts.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ObjectInvariant() ObjectInvariant() ObjectInvariant() ObjectInvariant()

Bietet Unterstützung für einen Contract.Provides support for a Contract.

(Inherited from Stream)
Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

Kopiert Bytes aus dem aktuellen gepufferten Stream in ein Array.Copies bytes from the current buffered stream to an array.

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>)

Kopiert Bytes aus dem gepufferten Stream in eine Bytespanne und verschiebt die Position im gepufferten Stream um die Anzahl der gelesenen Bytes.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) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32)

Liest eine Bytesequenz asynchron aus dem aktuellen Stream und setzt die Position in diesem Stream um die Anzahl der gelesenen Bytes nach vorn.Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Inherited from Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken)

Liest eine Folge von Bytes asynchron aus aktuellen Stream, erhöht die Position im Stream um die Anzahl der gelesenen Bytes und überwacht Abbruchanfragen.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) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken)

Liest eine Bytesequenz asynchron aus dem aktuellen gepufferten Stream und setzt die Position in diesem gepufferten Stream um die Anzahl der gelesenen Bytes nach vorn.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() ReadByte() ReadByte() ReadByte()

Liest ein Byte aus dem zugrunde liegenden Stream und gibt dieses in ein int umgewandelt zurück, bzw. wird -1 zurückgegeben, wenn das Ende des Streams erreicht ist.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) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin)

Legt die Position im aktuellen gepufferten Stream fest.Sets the position within the current buffered stream.

SetLength(Int64) SetLength(Int64) SetLength(Int64) SetLength(Int64)

Legt die Länge des gepufferten Streams fest.Sets the length of the buffered stream.

ToString() ToString() ToString() ToString()

Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt.Returns a string that represents the current object.

(Inherited from Object)
Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32)

Kopiert Bytes in den gepufferten Stream und verschiebt die aktuelle Position im gepufferten Stream um die Anzahl der geschriebenen Bytes.Copies bytes to the buffered stream and advances the current position within the buffered stream by the number of bytes written.

Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>)

Schreibt eine Bytesequenz in den aktuellen gepufferten Stream und setzt die aktuelle Position in diesem gepufferten Stream um die Anzahl der geschriebenen Bytes nach vorn.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) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32)

Schreibt eine Bytesequenz asynchron in den aktuellen Stream und setzt die aktuelle Position in diesem Stream um die Anzahl der geschriebenen Bytes nach vorn.Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Inherited from Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken)

Schreibt beim Überschreiben in einer abgeleiteten Klasse eine Folge von Bytes asynchron in den aktuellen Stream und erhöht die aktuelle Position im Stream um die Anzahl der geschriebenen Bytes und überwacht Abbruchanforderungen.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) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Schreibt beim Überschreiben in einer abgeleiteten Klasse eine Folge von Bytes asynchron in den aktuellen gepufferten Stream und erhöht die aktuelle Position im gepufferten Stream um die Anzahl der geschriebenen Bytes und überwacht Abbruchanforderungen.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) WriteByte(Byte) WriteByte(Byte) WriteByte(Byte)

Schreibt ein Byte an die aktuelle Position im gepufferten Stream.Writes a byte to the current position in the buffered stream.

Explizite Schnittstellenimplementierungen

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

Gibt alle vom Stream verwendeten Ressourcen frei.Releases all resources used by the Stream.

(Inherited from Stream)

Gilt für:

Siehe auch