BufferedStream 类

定义

添加缓冲层以在另一个流上读取和写入操作。 无法继承此类。

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
继承
BufferedStream
继承
属性

示例

下面的代码示例演示如何在 NetworkStream 类上使用 BufferedStream 类来提高某些 I/O 操作的性能。 在启动客户端之前,在远程计算机上启动服务器。 启动客户端时,将远程计算机名称指定为命令行参数。 根据 dataArraySizestreamBufferSize 常量来查看它们对性能的影响。

第一个示例显示客户端上运行的代码,第二个示例显示服务器上运行的代码。

示例 1:在客户端 上运行的代码

#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

示例 2:在服务器上运行的代码

#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

注解

缓冲区是内存中用于缓存数据的字节块,从而减少对操作系统的调用数。 缓冲区可提高读取和写入性能。 缓冲区可用于读取或写入,但绝不同时使用两者。 BufferedStreamReadWrite 方法会自动维护缓冲区。

重要

此类型实现 IDisposable 接口。 使用完该类型后,应直接或间接释放它。 若要直接释放类型,请在 try/catch 块中调用其 Dispose 方法。 若要间接处理它,请使用语言构造(如 using(在 C# 中)或 Using(在 Visual Basic 中)。 有关详细信息,请参阅 IDisposable 接口主题中的“使用实现 IDisposable 的对象”部分。

BufferedStream 可以围绕某些类型的流组成。 它提供用于读取和写入基础数据源或存储库的字节的实现。 使用 BinaryReaderBinaryWriter 读取和写入其他数据类型。 BufferedStream 旨在防止缓冲区在不需要缓冲区时减慢输入和输出速度。 如果始终读取和写入大于内部缓冲区大小的大小,则 BufferedStream 甚至可能不会分配内部缓冲区。 BufferedStream 还缓冲共享缓冲区中的读取和写入。 假设你几乎总是执行一系列读取或写入操作,但很少在两个读取或写入之间交替。

构造函数

BufferedStream(Stream)

使用默认缓冲区大小为 4096 字节初始化 BufferedStream 类的新实例。

BufferedStream(Stream, Int32)

使用指定的缓冲区大小初始化 BufferedStream 类的新实例。

属性

BufferSize

获取此缓冲流的缓冲区大小(以字节为单位)。

CanRead

获取一个值,该值指示当前流是否支持读取。

CanSeek

获取一个值,该值指示当前流是否支持查找。

CanTimeout

获取一个值,该值确定当前流是否可以超时。

(继承自 Stream)
CanWrite

获取一个值,该值指示当前流是否支持写入。

Length

获取流长度(以字节为单位)。

Position

获取当前流中的位置。

ReadTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试读取的时间。

(继承自 Stream)
UnderlyingStream

获取此缓冲流的基础 Stream 实例。

WriteTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时之前尝试写入的时间。

(继承自 Stream)

方法

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

开始异步读取操作。 (请考虑改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)

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

开始异步读取操作。 (请考虑改用 ReadAsync(Byte[], Int32, Int32)

(继承自 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步写入操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)

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

开始异步写入操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32)

(继承自 Stream)
Close()

关闭流并释放与当前缓冲流关联的任何资源(尤其是系统资源(例如套接字和文件句柄)。

Close()

关闭当前流并释放与当前流关联的任何资源(如套接字和文件句柄)。 请确保流已正确释放,而不是调用此方法。

(继承自 Stream)
CopyTo(Stream)

从当前流中读取字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyTo(Stream, Int32)

从当前缓冲流中读取字节并将其写入另一个流。

CopyTo(Stream, Int32)

从当前流中读取字节,并使用指定的缓冲区大小将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyToAsync(Stream)

从当前流异步读取字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyToAsync(Stream, CancellationToken)

使用指定的取消标记异步读取当前流中的字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyToAsync(Stream, Int32)

使用指定的缓冲区大小异步读取当前流中的字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

使用指定的缓冲区大小和取消标记异步读取当前缓冲流的字节并将其写入另一个流。

CopyToAsync(Stream, Int32, CancellationToken)

使用指定的缓冲区大小和取消令牌异步读取当前流中的字节并将其写入另一个流。 这两个流位置都是按复制的字节数进行高级的。

(继承自 Stream)
CreateObjRef(Type)

创建一个对象,其中包含生成用于与远程对象通信的代理所需的所有相关信息。

(继承自 MarshalByRefObject)
CreateWaitHandle()
已过时.
已过时.
已过时.

分配 WaitHandle 对象。

(继承自 Stream)
Dispose()

释放 Stream使用的所有资源。

(继承自 Stream)
Dispose(Boolean)

释放 Stream 使用的非托管资源,并选择性地释放托管资源。

(继承自 Stream)
DisposeAsync()

异步释放缓冲流使用的非托管资源。

DisposeAsync()

异步释放 Stream使用的非托管资源。

(继承自 Stream)
EndRead(IAsyncResult)

等待挂起的异步读取操作完成。 (请考虑改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)

EndRead(IAsyncResult)

等待挂起的异步读取完成。 (请考虑改用 ReadAsync(Byte[], Int32, Int32)

(继承自 Stream)
EndWrite(IAsyncResult)

结束异步写入操作并阻止,直到 I/O 操作完成。 (请考虑改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)

EndWrite(IAsyncResult)

结束异步写入操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32)

(继承自 Stream)
Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
Flush()

清除此流的所有缓冲区,并导致任何缓冲数据写入基础设备。

FlushAsync()

异步清除此流的所有缓冲区,并导致任何缓冲数据写入基础设备。

(继承自 Stream)
FlushAsync(CancellationToken)

异步清除此流的所有缓冲区,导致任何缓冲数据写入基础设备,并监视取消请求。

FlushAsync(CancellationToken)

异步清除此流的所有缓冲区,导致任何缓冲数据写入基础设备,并监视取消请求。

(继承自 Stream)
GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
ObjectInvariant()
已过时.

Contract提供支持。

(继承自 Stream)
Read(Byte[], Int32, Int32)

将字节从当前缓冲流复制到数组。

Read(Span<Byte>)

将字节从当前缓冲流复制到字节范围,并通过读取的字节数推进缓冲流中的位置。

Read(Span<Byte>)

在派生类中重写时,从当前流中读取字节序列,并通过读取的字节数推进流中的位置。

(继承自 Stream)
ReadAsync(Byte[], Int32, Int32)

从当前流异步读取字节序列,并通过读取的字节数推进流中的位置。

(继承自 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

从当前流异步读取字节序列,按读取的字节数推进流中的位置,并监视取消请求。

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

从当前流异步读取字节序列,按读取的字节数推进流中的位置,并监视取消请求。

(继承自 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

从当前缓冲流中异步读取字节序列,并通过读取的字节数推进缓冲流中的位置。

ReadAsync(Memory<Byte>, CancellationToken)

从当前流异步读取字节序列,按读取的字节数推进流中的位置,并监视取消请求。

(继承自 Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

至少从当前流中读取最小字节数,并通过读取的字节数提升流中的位置。

(继承自 Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

异步读取当前流的最小字节数,按读取的字节数推进流中的位置,并监视取消请求。

(继承自 Stream)
ReadByte()

从基础流中读取字节,并将字节强制转换为 int,或者从流末尾读取时返回 -1。

ReadExactly(Byte[], Int32, Int32)

从当前流中读取 count 字节数,并提升流中的位置。

(继承自 Stream)
ReadExactly(Span<Byte>)

从当前流中读取字节,并在填充 buffer 之前推进流中的位置。

(继承自 Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

从当前流异步读取 count 字节数,推进流中的位置,并监视取消请求。

(继承自 Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

从当前流异步读取字节,在填充 buffer 之前先行流中的位置,并监视取消请求。

(继承自 Stream)
Seek(Int64, SeekOrigin)

设置当前缓冲流中的位置。

SetLength(Int64)

设置缓冲流的长度。

ToString()

返回一个表示当前对象的字符串。

(继承自 Object)
Write(Byte[], Int32, Int32)

将字节复制到缓冲流,并通过写入的字节数推进缓冲流中的当前位置。

Write(ReadOnlySpan<Byte>)

将字节序列写入当前缓冲流,并通过写入的字节数推进此缓冲流中的当前位置。

Write(ReadOnlySpan<Byte>)

在派生类中重写时,将字节序列写入当前流,并通过写入的字节数推进此流中的当前位置。

(继承自 Stream)
WriteAsync(Byte[], Int32, Int32)

以异步方式将字节序列写入当前流,并通过写入的字节数推进此流中的当前位置。

(继承自 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

将字节序列异步写入当前流,按写入的字节数推进此流中的当前位置,并监视取消请求。

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

将字节序列异步写入当前流,按写入的字节数推进此流中的当前位置,并监视取消请求。

(继承自 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

将字节序列异步写入当前缓冲流,按写入的字节数推进此缓冲流的当前位置,并监视取消请求。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

将字节序列异步写入当前流,按写入的字节数推进此流中的当前位置,并监视取消请求。

(继承自 Stream)
WriteByte(Byte)

将字节写入缓冲流中的当前位置。

显式接口实现

IDisposable.Dispose()

释放 Stream使用的所有资源。

(继承自 Stream)

扩展方法

CopyToAsync(Stream, PipeWriter, CancellationToken)

使用取消令牌从 Stream 异步读取字节并将其写入指定的 PipeWriter

ConfigureAwait(IAsyncDisposable, Boolean)

配置如何执行从异步可释放项返回的任务的 await。

适用于

另请参阅