BufferedStream Classe

Définition

Ajoute une couche de mise en mémoire tampon aux opérations de lecture et d’écriture sur un autre flux.Adds a buffering layer to read and write operations on another stream. Cette classe ne peut pas être héritée.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
Héritage
BufferedStream
Héritage
Attributs

Exemples

Les exemples de code suivants montrent comment utiliser la classe BufferedStream sur la classe NetworkStream pour augmenter les performances de certaines opérations d’e/s.The following code examples show how to use the BufferedStream class over the NetworkStream class to increase the performance of certain I/O operations. Démarrez le serveur sur un ordinateur distant avant de démarrer le client.Start the server on a remote computer before starting the client. Spécifiez le nom de l’ordinateur distant en tant qu’argument de ligne de commande lors du démarrage du client.Specify the remote computer name as a command-line argument when starting the client. Faites varier les constantes d' dataArraySize et de streamBufferSize pour voir leur effet sur les performances.Vary the dataArraySize and streamBufferSize constants to view their effect on performance.

Le premier exemple montre le code qui s’exécute sur le client, et le deuxième exemple montre le code qui s’exécute sur le serveur.The first example shows the code that runs on the client, and the second example shows the code that runs on the server.

Exemple 1 : code qui s’exécute sur le clientExample 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

Exemple 2 : code qui s’exécute sur le serveurExample 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

Remarques

Une mémoire tampon est un bloc d’octets en mémoire utilisé pour mettre en cache des données, réduisant ainsi le nombre d’appels au système d’exploitation.A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. Les mémoires tampons améliorent les performances de lecture et d’écriture.Buffers improve read and write performance. Une mémoire tampon peut être utilisée pour la lecture ou l’écriture, mais jamais les deux simultanément.A buffer can be used for either reading or writing, but never both simultaneously. Les méthodes Read et Write de BufferedStream gérer automatiquement la mémoire tampon.The Read and Write methods of BufferedStream automatically maintain the buffer.

Important

Ce type implémente l'interface IDisposable.This type implements the IDisposable interface. Une fois que vous avez fini d’utiliser le type, vous devez le supprimer directement ou indirectement.When you have finished using the type, you should dispose of it either directly or indirectly. Pour supprimer directement le type Dispose, appelez sa méthode dans un bloc try/catch.To dispose of the type directly, call its Dispose method in a try/catch block. Pour la supprimer indirectement, utilisez une construction de langage telle que using (dans C#) ou Using (dans Visual Basic).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Pour plus d’informations, consultez la section « Utilisation d’un objet qui implémente IDisposable » dans la rubrique de l’interface IDisposable.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

BufferedStream peuvent être composés de certains types de flux.BufferedStream can be composed around certain types of streams. Il fournit des implémentations pour la lecture et l’écriture d’octets dans une source de données ou un référentiel sous-jacent.It provides implementations for reading and writing bytes to an underlying data source or repository. Utilisez BinaryReader et BinaryWriter pour la lecture et l’écriture d’autres types de données.Use BinaryReader and BinaryWriter for reading and writing other data types. BufferedStream est conçu pour empêcher la mémoire tampon de ralentir l’entrée et la sortie lorsque la mémoire tampon n’est pas nécessaire.BufferedStream is designed to prevent the buffer from slowing down input and output when the buffer is not needed. Si vous lisez et écrivez toujours des tailles supérieures à la taille de la mémoire tampon interne, BufferedStream pouvez même pas allouer la mémoire tampon interne.If you always read and write for sizes greater than the internal buffer size, then BufferedStream might not even allocate the internal buffer. BufferedStream également les lectures et les écritures dans une mémoire tampon partagée.BufferedStream also buffers reads and writes in a shared buffer. Il est supposé que vous effectuerez presque toujours une série de lectures ou d’écritures, mais que vous alternez rarement entre les deux.It is assumed that you will almost always be doing a series of reads or writes, but rarely alternate between the two of them.

Constructeurs

BufferedStream(Stream)

Initialise une nouvelle instance de la classe BufferedStream, avec une taille de mémoire tampon par défaut égale à 4 096 octets.Initializes a new instance of the BufferedStream class with a default buffer size of 4096 bytes.

BufferedStream(Stream, Int32)

Initialise une nouvelle instance de la classe BufferedStream avec la taille de mémoire tampon spécifiée.Initializes a new instance of the BufferedStream class with the specified buffer size.

Propriétés

BufferSize

Obtient la taille de la mémoire tampon en octets pour ce flux mis en mémoire tampon.Gets the buffer size in bytes for this buffered stream.

CanRead

Obtient une valeur indiquant si le flux actif prend en charge la lecture.Gets a value indicating whether the current stream supports reading.

CanSeek

Obtient une valeur indiquant si le flux actif prend en charge la recherche.Gets a value indicating whether the current stream supports seeking.

CanTimeout

Obtient une valeur qui détermine si le flux actuel peut dépasser le délai d'attente.Gets a value that determines whether the current stream can time out.

(Hérité de Stream)
CanWrite

Obtient une valeur indiquant si le flux actif prend en charge l'écriture.Gets a value indicating whether the current stream supports writing.

Length

Obtient la longueur du flux en octets.Gets the stream length in bytes.

Position

Obtient la position dans le flux actuel.Gets the position within the current stream.

ReadTimeout

Obtient ou définit une valeur, exprimée en millisecondes, qui définit la durée pendant laquelle le flux tentera d’effectuer la lecture avant dépassement du délai d’attente.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(Hérité de Stream)
UnderlyingStream

Obtient l’instance Stream sous-jacente pour ce flux mis en mémoire tampon.Gets the underlying Stream instance for this buffered stream.

WriteTimeout

Obtient ou définit une valeur, exprimée en millisecondes, qui définit la durée pendant laquelle le flux tentera d’écrire des données avant l’expiration du délai d’attente.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(Hérité de Stream)

Méthodes

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

Commence une opération de lecture asynchrone.Begins an asynchronous read operation. (Utilisez ReadAsync(Byte[], Int32, Int32, CancellationToken) à la place.)(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

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

Commence une opération d'écriture asynchrone.Begins an asynchronous write operation. (Utilisez WriteAsync(Byte[], Int32, Int32, CancellationToken) à la place.)(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Close()

Ferme le flux et libère toutes les ressources (en particulier les ressources système telles que les sockets et les handles de fichiers) associées au flux actuel en mémoire tampon.Closes the stream and releases any resources (especially system resources such as sockets and file handles) associated with the current buffered stream.

CopyTo(Stream)

Lit les octets du flux actuel et les écrit dans un autre flux.Reads the bytes from the current stream and writes them to another stream.

(Hérité de Stream)
CopyTo(Stream, Int32)

Lit les octets du flux mis en mémoire tampon actuel et les écrit dans un autre flux.Reads the bytes from the current buffered stream and writes them to another stream.

CopyToAsync(Stream)

Lit de façon asynchrone tous les octets du flux actuel et les écrit dans un autre flux.Asynchronously reads the bytes from the current stream and writes them to another stream.

(Hérité de Stream)
CopyToAsync(Stream, CancellationToken)

Lit de façon asynchrone les octets du flux actuel et les écrit dans un autre flux, en utilisant un jeton d’annulation spécifié.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(Hérité de Stream)
CopyToAsync(Stream, Int32)

Lit de façon asynchrone tous les octets du flux actuel et les écrit dans un autre flux, en utilisant une taille de mémoire tampon spécifiée.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Hérité de Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Lit de façon asynchrone les octets du flux mis en mémoire tampon actuel et les écrit dans un autre flux, en utilisant une taille de mémoire tampon et d’un jeton d’annulation spécifiés.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)

Crée un objet contenant toutes les informations appropriées requises pour générer un proxy permettant de communiquer avec un objet distant.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Hérité de MarshalByRefObject)
CreateWaitHandle()

Alloue un objet WaitHandle.Allocates a WaitHandle object.

(Hérité de Stream)
Dispose()

Libère toutes les ressources utilisées par Stream.Releases all resources used by the Stream.

(Hérité de Stream)
Dispose(Boolean)

Libère les ressources non managées utilisées par Stream et libère éventuellement les ressources managées.Releases the unmanaged resources used by the Stream and optionally releases the managed resources.

(Hérité de Stream)
DisposeAsync()

Libère de façon asynchrone les ressources non managées utilisées par le flux mis en mémoire tampon.Asynchronously releases the unmanaged resources used by the buffered stream.

EndRead(IAsyncResult)

Attend que l'opération de lecture asynchrone en attente se termine.Waits for the pending asynchronous read operation to complete. (Utilisez ReadAsync(Byte[], Int32, Int32, CancellationToken) à la place.)(Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

EndWrite(IAsyncResult)

Termine une opération d'écriture asynchrone et se bloque jusqu'à la fin de l'opération d'E/S.Ends an asynchronous write operation and blocks until the I/O operation is complete. (Utilisez WriteAsync(Byte[], Int32, Int32, CancellationToken) à la place.)(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.Determines whether the specified object is equal to the current object.

(Hérité de Object)
Flush()

Efface toutes les mémoires tampons pour ce flux et provoque l’écriture des données mises en mémoire tampon sur l’appareil sous-jacent.Clears all buffers for this stream and causes any buffered data to be written to the underlying device.

FlushAsync()

Efface de façon asynchrone toutes les mémoires tampons pour ce flux et provoque l'écriture des données mises en mémoire tampon sur l'appareil sous-jacent.Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Hérité de Stream)
FlushAsync(CancellationToken)

Efface de façon asynchrone toutes les mémoires tampons pour ce flux, provoque l'écriture des données mises en mémoire tampon sur l'appareil sous-jacent et surveille les requêtes d'annulation.Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

GetHashCode()

Sert de fonction de hachage par défaut.Serves as the default hash function.

(Hérité de Object)
GetLifetimeService()

Récupère l'objet de service de durée de vie en cours qui contrôle la stratégie de durée de vie de cette instance.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Hérité de MarshalByRefObject)
GetType()

Obtient le Type de l'instance actuelle.Gets the Type of the current instance.

(Hérité de Object)
InitializeLifetimeService()

Obtient un objet de service de durée de vie pour contrôler la stratégie de durée de vie de cette instance.Obtains a lifetime service object to control the lifetime policy for this instance.

(Hérité de MarshalByRefObject)
MemberwiseClone()

Crée une copie superficielle du Object actuel.Creates a shallow copy of the current Object.

(Hérité de Object)
MemberwiseClone(Boolean)

Crée une copie superficielle de l'objet MarshalByRefObject actuel.Creates a shallow copy of the current MarshalByRefObject object.

(Hérité de MarshalByRefObject)
ObjectInvariant()

Assure la prise en charge d'un Contract.Provides support for a Contract.

(Hérité de Stream)
Read(Byte[], Int32, Int32)

Copie les octets du flux actuel figurant dans la mémoire tampon dans un tableau.Copies bytes from the current buffered stream to an array.

Read(Span<Byte>)

Copie les octets depuis le flux mis en mémoire tampon actuel dans une plage d’octets et avance la position dans ce flux du nombre d’octets lus.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)

Lit de façon asynchrone une séquence d'octets dans le flux actuel et avance la position dans le flux du nombre d'octets lus.Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Hérité de Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

Lit de façon asynchrone une séquence d'octets dans le flux actuel, avance la position dans le flux du nombre d'octets lus et surveille les demandes d'annulation.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)

Lit de façon asynchrone une séquence d’octets dans le flux mis en mémoire tampon actuel et avance la position dans ce flux du nombre d’octets lus.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()

Lit un octet dans le flux sous-jacent et retourne un octet casté en int, ou retourne -1 en cas de lecture à partir de la fin du flux.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)

Définit la position dans le flux actuel mis en mémoire tampon.Sets the position within the current buffered stream.

SetLength(Int64)

Définit la longueur du flux mis en mémoire tampon.Sets the length of the buffered stream.

ToString()

Retourne une chaîne qui représente l'objet actif.Returns a string that represents the current object.

(Hérité de Object)
Write(Byte[], Int32, Int32)

Copie les octets dans le flux mis en mémoire tampon et avance la position actuelle dans ce flux du nombre d’octets écrits.Copies bytes to the buffered stream and advances the current position within the buffered stream by the number of bytes written.

Write(ReadOnlySpan<Byte>)

Écrit une séquence d’octets dans le flux mis en mémoire tampon actuel et avance la position actuelle dans ce flux du nombre d’octets écrits.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)

Écrit de façon asynchrone une séquence d'octets dans le flux actuel et avance la position actuelle dans le flux du nombre d'octets écrits.Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Hérité de Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

Écrit de façon asynchrone une séquence d'octets dans le flux actuel, avance la position actuelle dans ce flux du nombre d'octets écrits et surveille les demandes d'annulation.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)

Écrit de façon asynchrone une séquence d’octets dans le flux mis en mémoire tampon actuel, avance la position actuelle dans ce flux du nombre d’octets écrits et supervise les demandes d’annulation.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)

Écrit un octet à la position actuelle dans le flux mis en mémoire tampon.Writes a byte to the current position in the buffered stream.

Implémentations d’interfaces explicites

IDisposable.Dispose()

Libère toutes les ressources utilisées par Stream.Releases all resources used by the Stream.

(Hérité de Stream)

S’applique à

Voir aussi