BufferedStream Clase

Definición

Agrega una capa de almacenamiento en búfer para las operaciones de lectura y escritura en otra secuencia. Esta clase no puede heredarse.

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
[<System.Runtime.InteropServices.ComVisible(true)>]
type BufferedStream = class
    inherit Stream
Public NotInheritable Class BufferedStream
Inherits Stream
Herencia
BufferedStream
Herencia
Atributos

Ejemplos

En los ejemplos de código siguientes se muestra cómo usar la BufferedStream clase sobre la NetworkStream clase para aumentar el rendimiento de determinadas operaciones de E/S. Inicie el servidor en un equipo remoto antes de iniciar el cliente. Especifique el nombre del equipo remoto como argumento de línea de comandos al iniciar el cliente. Varía las dataArraySize constantes y streamBufferSize para ver su efecto en el rendimiento.

En el primer ejemplo se muestra el código que se ejecuta en el cliente y el segundo ejemplo muestra el código que se ejecuta en el servidor.

Ejemplo 1: Código que se ejecuta en el cliente

#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");
    }
}
module Client

open System
open System.IO
open System.Net
open System.Net.Sockets

let dataArraySize    =   100
let streamBufferSize =  1000
let numberOfLoops    = 10000

let sendData (netStream: Stream) (bufStream: Stream) =
    // Create random data to send to the server.
    let dataToSend = Array.zeroCreate dataArraySize
    Random().NextBytes dataToSend

    // Send the data using the NetworkStream.
    printfn "Sending data using NetworkStream."
    let startTime = DateTime.Now
    for _ = 0 to numberOfLoops - 1 do
        netStream.Write(dataToSend, 0, dataToSend.Length)
    let networkTime = (DateTime.Now - startTime).TotalSeconds
    printfn $"{numberOfLoops * dataToSend.Length} bytes sent in {networkTime:F1} seconds.\n"

    // Send the data using the BufferedStream.
    printfn "Sending data using BufferedStream."
    let startTime = DateTime.Now
    for _ = 0 to numberOfLoops - 1 do
        bufStream.Write(dataToSend, 0, dataToSend.Length)
    bufStream.Flush()
    let bufferedTime = (DateTime.Now - startTime).TotalSeconds
    printfn $"{numberOfLoops * dataToSend.Length} bytes sent in {bufferedTime:F1} seconds.\n"

    // Print the ratio of write times.
    printfn $"""Sending data using the buffered network stream was {networkTime / bufferedTime:P0} {if bufferedTime < networkTime then "faster" else "slower"} than using the network stream alone."""
    printfn ""

let receiveData (netStream: Stream) (bufStream: Stream) =
    let mutable bytesReceived = 0
    let receivedData = Array.zeroCreate dataArraySize

    // Receive data using the NetworkStream.
    printfn "Receiving data using NetworkStream."
    let startTime = DateTime.Now
    while bytesReceived < numberOfLoops * receivedData.Length do
        bytesReceived <- bytesReceived + netStream.Read(receivedData, 0, receivedData.Length)
    let networkTime = (DateTime.Now - startTime).TotalSeconds
    printfn $"{bytesReceived} bytes received in {networkTime:F1} seconds.\n"

    // Receive data using the BufferedStream.
    printfn "Receiving data using BufferedStream."
    bytesReceived <- 0
    let startTime = DateTime.Now

    let mutable numBytesToRead = receivedData.Length

    let mutable broken = false
    while not broken && numBytesToRead > 0 do
        // Read may return anything from 0 to numBytesToRead.
        let n = bufStream.Read(receivedData,0, receivedData.Length)
        // The end of the file is reached.
        if n = 0 then
            broken <- true
        else
            bytesReceived <- bytesReceived + n
            numBytesToRead <- numBytesToRead - n

    let bufferedTime = (DateTime.Now - startTime).TotalSeconds
    printfn $"{bytesReceived} bytes received in {bufferedTime:F1} seconds.\n"

    // Print the ratio of read times.
    printfn $"""Receiving data using the buffered network stream was {networkTime / bufferedTime:P0} {if bufferedTime < networkTime then "faster" else "slower"} than using the network stream alone."""

[<EntryPoint>]
let main args =
    // Check that an argument was specified when the
    // program was invoked.
    if args.Length = 0 then
        printfn "Error: The name of the host computer must be specified when the program is invoked."
    else
        let remoteName = args[0]

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

        clientSocket.Connect(IPEndPoint(Dns.GetHostEntry(remoteName).AddressList[0], 1800))

        printfn "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.
        use netStream = new NetworkStream(clientSocket, true)
        use bufStream = new BufferedStream(netStream, streamBufferSize)
        // Check whether the underlying stream supports seeking.
        printfn $"""NetworkStream {if bufStream.CanSeek then "supports" else "does not support"} seeking.\n"""

        // Send and receive data.
        if bufStream.CanWrite then
            sendData netStream bufStream
        if bufStream.CanRead then
            receiveData netStream bufStream

        // When bufStream is closed, netStream is in turn
        // closed, which in turn shuts down the connection
        // and closes clientSocket.
        printfn "\nShutting down the connection."
        bufStream.Close()
    0
' 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

Ejemplo 2: Código que se ejecuta en el servidor

#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();
        }
    }
}
module Server

open System
open System.Net
open System.Net.Sockets

// This is a Windows Sockets 2 error code.
let WSAETIMEDOUT = 10060

let mutable bytesReceived = -1 
let mutable totalReceived = 0
let receivedData = Array.zeroCreate 2000000

// Create random data to send to the client.
let dataToSend = Array.zeroCreate 2000000
Random().NextBytes dataToSend

let ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0]

let ipEndpoint = IPEndPoint(ipAddress, 1800)

// Create a socket and listen for incoming connections.
let serverSocket = 
    use 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.
    listenSocket.Accept()

printfn "Server is connected.\n"

try
    // Send data to the client.
    printf "Sending data ... "
    let bytesSent = serverSocket.Send(dataToSend, 0, dataToSend.Length, SocketFlags.None)
    printfn $"{bytesSent} bytes sent.\n"

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

    // Receive data from the client.
    printf "Receiving data ... "
    try
        try
            while bytesReceived <> 0 do
                bytesReceived <- serverSocket.Receive(receivedData, 0, receivedData.Length, SocketFlags.None)
                totalReceived <- totalReceived + bytesReceived

        with :? SocketException as e ->
            if e.ErrorCode = WSAETIMEDOUT then
                // Data was not received within the given time.
                // Assume that the transmission has ended.
                ()
            else
                printfn $"{e.GetType().Name}: {e.Message}\n"
    finally
        printfn $"{totalReceived} bytes received.\n"
finally
    serverSocket.Shutdown SocketShutdown.Both
    printfn "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

Comentarios

Un búfer es un bloque de bytes en memoria que se usa para almacenar en caché los datos, lo que reduce el número de llamadas al sistema operativo. Los búferes mejoran el rendimiento de lectura y escritura. Se puede usar un búfer para leer o escribir, pero nunca ambos simultáneamente. Los Read métodos y Write de BufferedStream mantener automáticamente el búfer.

Importante

Este tipo implementa la interfaz IDisposable. Cuando haya terminado de utilizar el tipo, debe desecharlo directa o indirectamente. Para eliminar el tipo directamente, llame a su método Dispose en un bloque try/catch. Para deshacerse de él indirectamente, use una construcción de lenguaje como using (en C#) o Using (en Visual Basic). Para más información, vea la sección "Uso de objetos que implementan IDisposable" en el tema de la interfaz IDisposable.

BufferedStream se puede componer alrededor de ciertos tipos de secuencias. Proporciona implementaciones para leer y escribir bytes en un origen de datos o repositorio subyacente. Use BinaryReader y BinaryWriter para leer y escribir otros tipos de datos. BufferedStream está diseñado para evitar que el búfer ralentice la entrada y salida cuando no se necesite el búfer. Si siempre lee y escribe para tamaños mayores que el tamaño del búfer interno, BufferedStream es posible que ni siquiera asigne el búfer interno. BufferedStream también almacena en búfer las lecturas y escrituras en un búfer compartido. Se supone que casi siempre va a realizar una serie de lecturas o escrituras, pero rara vez alterna entre las dos.

Constructores

BufferedStream(Stream)

Inicializa una nueva instancia de la clase BufferedStream con un tamaño de búfer predeterminado de 4096 bytes.

BufferedStream(Stream, Int32)

Inicializa una nueva instancia de la clase BufferedStream con el tamaño de búfer especificado.

Propiedades

BufferSize

Obtiene el tamaño de búfer en bytes de esta secuencia almacenada en búfer.

CanRead

Obtiene un valor que indica si la secuencia actual admite lectura.

CanSeek

Obtiene un valor que indica si la secuencia actual admite búsquedas.

CanTimeout

Obtiene un valor que determina si se puede agotar el tiempo de espera de la secuencia actual.

(Heredado de Stream)
CanWrite

Obtiene un valor que indica si la secuencia actual admite escritura.

Length

Obtiene la longitud de la secuencia en bytes.

Position

Obtiene la posición dentro de la secuencia actual.

ReadTimeout

Obtiene o establece un valor, en milisegundos, que determina durante cuánto tiempo la secuencia intentará realizar operaciones de lectura antes de que se agote el tiempo de espera.

(Heredado de Stream)
UnderlyingStream

Obtiene la instancia de Stream subyacente de esta secuencia almacenada en búfer.

WriteTimeout

Obtiene o establece un valor, en milisegundos, que determina durante cuánto tiempo la secuencia intentará realizar operaciones de escritura antes de que se agote el tiempo de espera.

(Heredado de Stream)

Métodos

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

Comienza una operación de lectura asincrónica. (Considere usar ReadAsync(Byte[], Int32, Int32, CancellationToken) en su lugar).

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

Comienza una operación de lectura asincrónica. (Considere usar ReadAsync(Byte[], Int32, Int32) en su lugar).

(Heredado de Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Comienza una operación de escritura asincrónica. (Considere usar WriteAsync(Byte[], Int32, Int32, CancellationToken) en su lugar).

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

Comienza una operación de escritura asincrónica. (Considere usar WriteAsync(Byte[], Int32, Int32) en su lugar).

(Heredado de Stream)
Close()

Cierra la secuencia y libera los recursos (especialmente recursos del sistema como sockets e identificadores de archivos) asociados a la secuencia actual en el búfer.

Close()

Cierra la secuencia actual y libera todos los recursos (como sockets e identificadores de archivo) asociados a esta. En lugar de llamar a este método, asegúrese de que la secuencia se desecha correctamente.

(Heredado de Stream)
CopyTo(Stream)

Lee los bytes de la secuencia actual y los escribe en otra secuencia de destino. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyTo(Stream, Int32)

Lee los bytes de la secuencia almacenada en búfer actual y los escribe en otra secuencia.

CopyTo(Stream, Int32)

Lee todos los bytes de la secuencia actual y los escribe en otra secuencia, usando el tamaño de búfer especificado. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyToAsync(Stream)

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyToAsync(Stream, CancellationToken)

Lee de forma asincrónica los bytes de la secuencia actual y los escribe en otra secuencia mediante un token de cancelación especificado. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyToAsync(Stream, Int32)

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia, usando el tamaño de búfer especificado. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Lee asincrónicamente los bytes de la secuencia almacenada en búfer actual y los escribe en otra secuencia, utilizando el tamaño de búfer y el token de cancelación especificados.

CopyToAsync(Stream, Int32, CancellationToken)

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia, utilizando el tamaño de búfer y el token de cancelación especificados. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.

(Heredado de MarshalByRefObject)
CreateWaitHandle()
Obsoletos.
Obsoletos.
Obsoletos.

Asigna un objeto WaitHandle.

(Heredado de Stream)
Dispose()

Libera todos los recursos que usa Stream.

(Heredado de Stream)
Dispose(Boolean)

Libera los recursos no administrados que usa Stream y, de forma opcional, libera los recursos administrados.

(Heredado de Stream)
DisposeAsync()

Libera de forma asincrónica los recursos no administrados usados por la secuencia almacenada en búfer.

DisposeAsync()

Libera de forma asincrónica los recursos no administrados usados por Stream.

(Heredado de Stream)
EndRead(IAsyncResult)

Espera a que se complete la operación asincrónica de lectura que se encuentra pendiente. (Considere usar ReadAsync(Byte[], Int32, Int32, CancellationToken) en su lugar).

EndRead(IAsyncResult)

Espera a que se complete la lectura asincrónica que se encuentra pendiente. (Considere usar ReadAsync(Byte[], Int32, Int32) en su lugar).

(Heredado de Stream)
EndWrite(IAsyncResult)

Termina una operación de escritura asincrónica y se bloquea hasta que se completa la operación de E/S. (Considere usar WriteAsync(Byte[], Int32, Int32, CancellationToken) en su lugar).

EndWrite(IAsyncResult)

Finaliza una operación de escritura asincrónica. (Considere usar WriteAsync(Byte[], Int32, Int32) en su lugar).

(Heredado de Stream)
Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
Flush()

Borra todos los búferes para esta secuencia y hace que los datos almacenados en búfer se escriban en el dispositivo subyacente.

FlushAsync()

Borra asincrónicamente todos los búferes de esta secuencia y hace que los datos almacenados en búfer se escriban en el dispositivo subyacente.

(Heredado de Stream)
FlushAsync(CancellationToken)

Borra asincrónicamente todos los búferes de esta secuencia, y hace que todos los datos almacenados en búfer se escriban en el dispositivo subyacente y supervisa las solicitudes de cancelación.

FlushAsync(CancellationToken)

Borra asincrónicamente todos los búferes de esta secuencia, y hace que todos los datos almacenados en búfer se escriban en el dispositivo subyacente y supervisa las solicitudes de cancelación.

(Heredado de Stream)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetLifetimeService()
Obsoletos.

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.

(Heredado de MarshalByRefObject)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
InitializeLifetimeService()
Obsoletos.

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.

(Heredado de MarshalByRefObject)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.

(Heredado de MarshalByRefObject)
ObjectInvariant()
Obsoletos.

Proporciona compatibilidad con una clase Contract.

(Heredado de Stream)
Read(Byte[], Int32, Int32)

Copia bytes, procedentes de la secuencia actual almacenada en el búfer, en una matriz.

Read(Span<Byte>)

Copia los bytes de la secuencia almacenada en búfer actual en un intervalo de bytes y avanza la posición dentro de la secuencia almacenada en búfer el número de bytes leídos.

Read(Span<Byte>)

Cuando se reemplaza en una clase derivada, se lee una secuencia de bytes en la secuencia actual y se hace avanzar la posición dentro de la secuencia el número de bytes leídos.

(Heredado de Stream)
ReadAsync(Byte[], Int32, Int32)

Lee asincrónicamente una secuencia de bytes de la secuencia actual y avanza la posición en esta secuencia según el número de bytes leídos.

(Heredado de Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

Lee de forma asincrónica una secuencia de bytes en la secuencia actual, se hace avanzar la posición dentro de la secuencia el número de bytes leídos y controla las solicitudes de cancelación.

ReadAsync(Byte[], Int32, Int32, CancellationToken)

Lee de forma asincrónica una secuencia de bytes en la secuencia actual, se hace avanzar la posición dentro de la secuencia el número de bytes leídos y controla las solicitudes de cancelación.

(Heredado de Stream)
ReadAsync(Memory<Byte>, CancellationToken)

Lee de forma asincrónica una secuencia de bytes de la secuencia almacenada en búfer actual y avanza la posición en esta secuencia almacenada en búfer según el número de bytes leídos.

ReadAsync(Memory<Byte>, CancellationToken)

Lee de forma asincrónica una secuencia de bytes en la secuencia actual, se hace avanzar la posición dentro de la secuencia el número de bytes leídos y controla las solicitudes de cancelación.

(Heredado de Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

Lee al menos un número mínimo de bytes de la secuencia actual y avanza la posición dentro de la secuencia por el número de bytes leídos.

(Heredado de Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

Lee de forma asincrónica al menos un número mínimo de bytes de la secuencia actual, avanza la posición dentro de la secuencia por el número de bytes leídos y supervisa las solicitudes de cancelación.

(Heredado de Stream)
ReadByte()

Lee un byte de la secuencia subyacente y devuelve el byte convertido en un int, o devuelve -1 si se lee desde el final de la secuencia.

ReadExactly(Byte[], Int32, Int32)

count Lee el número de bytes de la secuencia actual y avanza la posición dentro de la secuencia.

(Heredado de Stream)
ReadExactly(Span<Byte>)

Lee bytes de la secuencia actual y avanza la posición dentro de la secuencia hasta buffer que se rellena .

(Heredado de Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

Lee count de forma asincrónica el número de bytes de la secuencia actual, avanza la posición dentro de la secuencia y supervisa las solicitudes de cancelación.

(Heredado de Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

Lee de forma asincrónica los bytes de la secuencia actual, avanza la posición dentro de la secuencia hasta buffer que se rellena y supervisa las solicitudes de cancelación.

(Heredado de Stream)
Seek(Int64, SeekOrigin)

Establece la posición dentro de la secuencia almacenada en búfer actualmente.

SetLength(Int64)

Establece la longitud de la secuencia almacenada en el búfer.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
Write(Byte[], Int32, Int32)

Copia bytes en la secuencia almacenada en el búfer y avanza la posición actual dentro de la secuencia almacenada en el búfer según el número de bytes escritos.

Write(ReadOnlySpan<Byte>)

Escribe una secuencia de bytes en la secuencia almacenada en búfer actual y avanza la posición actual dentro de esta secuencia almacenada en búfer el número de bytes escritos.

Write(ReadOnlySpan<Byte>)

Cuando se reemplaza en una clase derivada, se escribe una secuencia de bytes en la secuencia actual y se hace avanzar la posición actual dentro de la secuencia el número de bytes escritos.

(Heredado de Stream)
WriteAsync(Byte[], Int32, Int32)

Escribe asincrónicamente una secuencia de bytes en la secuencia actual y avanza la posición actual en esta secuencia según el número de bytes escritos.

(Heredado de Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

Escribe de forma asincrónica una secuencia de bytes en la secuencia actual, se hace avanzar la posición actual dentro de la secuencia el número de bytes escritos y controla las solicitudes de cancelación.

WriteAsync(Byte[], Int32, Int32, CancellationToken)

Escribe de forma asincrónica una secuencia de bytes en la secuencia actual, se hace avanzar la posición actual dentro de la secuencia el número de bytes escritos y controla las solicitudes de cancelación.

(Heredado de Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Escribe de forma asincrónica una secuencia de bytes en la secuencia almacenada en búfer actual, avanza la posición actual dentro de la secuencia almacenada en búfer el número de bytes escritos y controla las solicitudes de cancelación.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Escribe de forma asincrónica una secuencia de bytes en la secuencia actual, se hace avanzar la posición actual dentro de la secuencia el número de bytes escritos y controla las solicitudes de cancelación.

(Heredado de Stream)
WriteByte(Byte)

Escribe un byte en la posición actual de la secuencia almacenada en el búfer.

Implementaciones de interfaz explícitas

IDisposable.Dispose()

Libera todos los recursos que usa Stream.

(Heredado de Stream)

Métodos de extensión

ConfigureAwait(IAsyncDisposable, Boolean)

Configura la forma en la que se realizan las expresiones await en las tareas devueltas desde un elemento asincrónico descartable.

Se aplica a

Consulte también