BufferedStream Classe

Definizione

Aggiunge un livello di buffer per operazioni di lettura e scrittura in un altro flusso. La classe non può essere ereditata.

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
Ereditarietà
BufferedStream
Ereditarietà
Attributi

Esempio

Gli esempi di codice seguenti illustrano come usare la BufferedStream classe sulla NetworkStream classe per aumentare le prestazioni di determinate operazioni di I/O. Avviare il server in un computer remoto prima di avviare il client. Specificare il nome del computer remoto come argomento della riga di comando quando si avvia il client. Variare le costanti e streamBufferSize per visualizzare l'effetto dataArraySize sulle prestazioni.

Il primo esempio mostra il codice eseguito nel client e il secondo esempio mostra il codice eseguito nel server.

Esempio 1: Codice in esecuzione nel 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");
    }
}
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

Esempio 2: Codice in esecuzione nel 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();
        }
    }
}
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

Commenti

Un buffer è un blocco di byte in memoria usato per memorizzare nella cache i dati, riducendo così il numero di chiamate al sistema operativo. I buffer migliorano le prestazioni di lettura e scrittura. Un buffer può essere usato per la lettura o la scrittura, ma non entrambi contemporaneamente. I Read metodi e Write di BufferedStream mantenere automaticamente il buffer.

Importante

Il tipo implementa l'interfaccia IDisposable. Dopo aver utilizzato il tipo, è necessario eliminarlo direttamente o indirettamente. Per eliminare direttamente il tipo, chiamare il metodo Dispose in un blocco try/catch. Per eliminarlo indirettamente, utilizzare un costrutto di linguaggio come ad esempio using in C# o Using in Visual Basic. Per altre informazioni, vedere la sezione "Uso di un oggetto che implementa IDisposable" nell'argomento relativo all'interfaccia IDisposable.

BufferedStream può essere composto intorno a determinati tipi di flussi. Fornisce implementazioni per la lettura e la scrittura di byte in un'origine dati o in un repository sottostante. Usare BinaryReader e per leggere e BinaryWriter scrivere altri tipi di dati. BufferedStream è progettato per impedire al buffer di rallentare l'input e l'output quando il buffer non è necessario. Se si legge sempre e si scrive per dimensioni superiori alle dimensioni del buffer interno, potrebbe BufferedStream anche non allocare il buffer interno. BufferedStream anche i buffer legge e scrive in un buffer condiviso. Si presuppone che si stia quasi sempre facendo una serie di letture o scritture, ma raramente alternativamente tra i due.

Costruttori

BufferedStream(Stream)

Inizializza una nuova istanza della classe BufferedStream con una dimensione predefinita del buffer di 4096 byte.

BufferedStream(Stream, Int32)

Inizializza una nuova istanza della classe BufferedStream con la dimensione specificata del buffer.

Proprietà

BufferSize

Ottiene le dimensioni del buffer in byte per questo flusso memorizzato nel buffer.

CanRead

Ottiene un valore che indica se il flusso corrente supporta la lettura.

CanSeek

Ottiene un valore che indica se il flusso corrente supporta la ricerca.

CanTimeout

Ottiene un valore che determina se il flusso corrente prevede il timeout.

(Ereditato da Stream)
CanWrite

Ottiene un valore che indica se il flusso corrente supporta la scrittura.

Length

Ottiene la lunghezza del flusso in byte.

Position

Ottiene la posizione all'interno del flusso corrente.

ReadTimeout

Ottiene o imposta un valore, in millisecondi, che determina per quanto tempo il flusso tenterà la lettura prima del timeout.

(Ereditato da Stream)
UnderlyingStream

Ottiene l'istanza di Stream sottostante per questo flusso memorizzato nel buffer.

WriteTimeout

Ottiene o imposta un valore, in millisecondi, che determina per quanto tempo il flusso tenterà la scrittura prima del timeout.

(Ereditato da Stream)

Metodi

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

Inizia un'operazione di lettura asincrona. Si consiglia di usare ReadAsync(Byte[], Int32, Int32, CancellationToken).

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

Inizia un'operazione di lettura asincrona. Si consiglia di usare ReadAsync(Byte[], Int32, Int32).

(Ereditato da Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Inizia un'operazione di scrittura asincrona. Si consiglia di usare WriteAsync(Byte[], Int32, Int32, CancellationToken).

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

Inizia un'operazione di scrittura asincrona. Si consiglia di usare WriteAsync(Byte[], Int32, Int32).

(Ereditato da Stream)
Close()

Chiude il flusso e libera le risorse, in particolare le risorse di sistema come socket e handle di file, associate al flusso corrente memorizzato nel buffer.

Close()

Chiude il flusso corrente e libera le risorse, come socket e handle di file, ad esso associate. Anziché chiamare questo metodo, assicurarsi che il flusso sia eliminato correttamente.

(Ereditato da Stream)
CopyTo(Stream)

Legge i byte dal flusso corrente e li scrive in un altro flusso. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati.

(Ereditato da Stream)
CopyTo(Stream, Int32)

Legge i byte dal flusso memorizzato nel buffer corrente e li scrive in un altro flusso.

CopyTo(Stream, Int32)

Legge tutti i byte dal flusso corrente e li scrive in un altro flusso, usando una dimensione di buffer specificata. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati.

(Ereditato da Stream)
CopyToAsync(Stream)

Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati.

(Ereditato da Stream)
CopyToAsync(Stream, CancellationToken)

Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso, usando un token di annullamento specificato. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati.

(Ereditato da Stream)
CopyToAsync(Stream, Int32)

Legge in modo asincrono tutti i byte dal flusso corrente e li scrive in un altro flusso, utilizzando una dimensione di buffer specificata. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati.

(Ereditato da Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Legge in modo asincrono i byte dal flusso memorizzato nel buffer corrente e li scrive in un altro flusso, usando dimensioni del buffer e un token di annullamento specificati.

CopyToAsync(Stream, Int32, CancellationToken)

Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso, usando una dimensione di buffer specificata e un token di annullamento. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati.

(Ereditato da Stream)
CreateObjRef(Type)

Consente di creare un oggetto che contiene tutte le informazioni rilevanti necessarie per la generazione del proxy utilizzato per effettuare la comunicazione con un oggetto remoto.

(Ereditato da MarshalByRefObject)
CreateWaitHandle()
Obsoleti.
Obsoleti.
Obsoleti.

Alloca un oggetto WaitHandle.

(Ereditato da Stream)
Dispose()

Rilascia tutte le risorse usate da Stream.

(Ereditato da Stream)
Dispose(Boolean)

Rilascia le risorse non gestite usate da Stream e, facoltativamente, le risorse gestite.

(Ereditato da Stream)
DisposeAsync()

Consente di rilasciare in modo asincrono le risorse non gestite usate dal flusso memorizzato nel buffer.

DisposeAsync()

Consente di liberare in modo asincrono le risorse non gestite utilizzate da Stream.

(Ereditato da Stream)
EndRead(IAsyncResult)

Attende il completamento dell'operazione di lettura asincrona in sospeso. Si consiglia di usare ReadAsync(Byte[], Int32, Int32, CancellationToken).

EndRead(IAsyncResult)

Attende il completamento della lettura asincrona in sospeso. Si consiglia di usare ReadAsync(Byte[], Int32, Int32).

(Ereditato da Stream)
EndWrite(IAsyncResult)

Termina un'operazione di scrittura asincrona, rimanendo bloccato fino al completamento dell'operazione di I/O. Si consiglia di usare WriteAsync(Byte[], Int32, Int32, CancellationToken).

EndWrite(IAsyncResult)

Termina un'operazione di scrittura asincrona. Si consiglia di usare WriteAsync(Byte[], Int32, Int32).

(Ereditato da Stream)
Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
Flush()

Consente di cancellare i dati di tutti i buffer del flusso e la scrittura dei dati memorizzati nel buffer nella periferica sottostante.

FlushAsync()

Cancella in modo asincrono i dati di tutti i buffer del flusso e determina la scrittura dei dati memorizzati nel buffer nel dispositivo sottostante.

(Ereditato da Stream)
FlushAsync(CancellationToken)

Cancella in modo asincrono i dati di tutti i buffer del flusso, determina la scrittura dei dati memorizzati nel buffer nel dispositivo sottostante e monitora le richieste di annullamento.

FlushAsync(CancellationToken)

Cancella in modo asincrono i dati di tutti i buffer del flusso, determina la scrittura dei dati memorizzati nel buffer nel dispositivo sottostante e monitora le richieste di annullamento.

(Ereditato da Stream)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLifetimeService()
Obsoleti.

Consente di recuperare l'oggetto servizio di durata corrente per controllare i criteri di durata per l'istanza.

(Ereditato da MarshalByRefObject)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
InitializeLifetimeService()
Obsoleti.

Ottiene un oggetto servizio di durata per controllare i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia dei riferimenti dell'oggetto MarshalByRefObject corrente.

(Ereditato da MarshalByRefObject)
ObjectInvariant()
Obsoleti.

Fornisce supporto per un oggetto Contract.

(Ereditato da Stream)
Read(Byte[], Int32, Int32)

Copia i byte dal flusso correntemente memorizzato nel buffer in una matrice.

Read(Span<Byte>)

Copia byte dal flusso memorizzato nel buffer corrente a un intervallo di byte e sposta in avanti la posizione all'interno del flusso memorizzato nel buffer in base al numero di byte letti.

Read(Span<Byte>)

Quando ne viene eseguito l'override in una classe derivata, legge una sequenza di byte dal flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte letti.

(Ereditato da Stream)
ReadAsync(Byte[], Int32, Int32)

Legge in modo asincrono una sequenza di byte dal flusso corrente e passa alla posizione successiva nel flusso in base al numero di byte letti.

(Ereditato da Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

Legge in modo asincrono una sequenza di byte dal flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte letti e monitora le richieste di annullamento.

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

Legge in modo asincrono una sequenza di byte dal flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte letti e monitora le richieste di annullamento.

(Ereditato da Stream)
ReadAsync(Memory<Byte>, CancellationToken)

Legge in modo asincrono una sequenza di byte dal flusso memorizzato nel buffer corrente e sposta in avanti la posizione all'interno del flusso memorizzato nel buffer in base al numero di byte letti.

ReadAsync(Memory<Byte>, CancellationToken)

Legge in modo asincrono una sequenza di byte dal flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte letti e monitora le richieste di annullamento.

(Ereditato da Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

Legge almeno un numero minimo di byte dal flusso corrente e sposta in avanti la posizione all'interno del flusso in base al numero di byte letti.

(Ereditato da Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

Legge in modo asincrono almeno un numero minimo di byte dal flusso corrente, sposta in avanti la posizione all'interno del flusso in base al numero di byte letti e monitora le richieste di annullamento.

(Ereditato da Stream)
ReadByte()

Legge un byte dal flusso sottostante e restituisce il cast di byte su un parametro int o restituisce -1 se la lettura viene eseguita a partire dalla fine del flusso.

ReadExactly(Byte[], Int32, Int32)

count Legge il numero di byte dal flusso corrente e sposta in avanti la posizione all'interno del flusso.

(Ereditato da Stream)
ReadExactly(Span<Byte>)

Legge i byte dal flusso corrente e sposta in avanti la posizione all'interno del flusso fino a quando non viene riempito.buffer

(Ereditato da Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

Legge in modo asincrono count il numero di byte dal flusso corrente, sposta in avanti la posizione all'interno del flusso e monitora le richieste di annullamento.

(Ereditato da Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

Legge in modo asincrono i byte dal flusso corrente, sposta la posizione all'interno del flusso fino a quando non buffer viene riempita e monitora le richieste di annullamento.

(Ereditato da Stream)
Seek(Int64, SeekOrigin)

Imposta la posizione all'interno del flusso corrente memorizzato nel buffer.

SetLength(Int64)

Imposta la lunghezza del flusso memorizzato nel buffer.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
Write(Byte[], Int32, Int32)

Copia i byte nel flusso memorizzato nel buffer e sposta la posizione corrente, all'interno del flusso memorizzato nel buffer, in base al numero di byte scritto.

Write(ReadOnlySpan<Byte>)

Scrive una sequenza di byte nel flusso memorizzato nel buffer corrente e sposta in avanti la posizione nel flusso in base al numero di byte scritti.

Write(ReadOnlySpan<Byte>)

Quando ne viene eseguito l'override in una classe derivata, scrive una sequenza di byte nel flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte scritti.

(Ereditato da Stream)
WriteAsync(Byte[], Int32, Int32)

Scrive in modo asincrono una sequenza di byte nel flusso corrente e passa alla posizione successiva nel flusso in base al numero di byte scritti.

(Ereditato da Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

Scrive in modo asincrono una sequenza di byte nel flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte scritti e monitora le richieste di annullamento.

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

Scrive in modo asincrono una sequenza di byte nel flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte scritti e monitora le richieste di annullamento.

(Ereditato da Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Scrive in modo asincrono una sequenza di byte nel flusso memorizzato nel buffer corrente e sposta in avanti la posizione all'interno del flusso memorizzato nel buffer corrente in base al numero di byte scritti ed esegue il monitoraggio delle richieste di annullamento.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Scrive in modo asincrono una sequenza di byte nel flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte scritti e monitora le richieste di annullamento.

(Ereditato da Stream)
WriteByte(Byte)

Scrive un byte nella posizione corrente all'interno del flusso memorizzato nel buffer.

Implementazioni dell'interfaccia esplicita

IDisposable.Dispose()

Rilascia tutte le risorse usate da Stream.

(Ereditato da Stream)

Metodi di estensione

ConfigureAwait(IAsyncDisposable, Boolean)

Consente di configurare la modalità di esecuzione delle espressioni await per le attività restituite da un elemento disposable asincrono.

Si applica a

Vedi anche