エクスポート (0) 印刷
すべて展開

BufferedStream クラス

他のストリームに対する読み取り操作および書き込み操作にバッファリング層を追加します。このクラスは継承できません。

名前空間: System.IO
アセンブリ: mscorlib (mscorlib.dll 内)

[ComVisibleAttribute(true)] 
public sealed class BufferedStream : Stream
/** @attribute ComVisibleAttribute(true) */ 
public final class BufferedStream extends Stream
ComVisibleAttribute(true) 
public final class BufferedStream extends Stream

ファイルの作成およびテキストのファイルへの書き込みの例については、「方法 : ファイルにテキストを書き込む」を参照してください。ファイルからのテキストの読み取りの例については、「方法 : ファイルからテキストを読み取る」を参照してください。バイナリ ファイルの読み取りおよび書き込みの例については、「方法 : 新しく作成されたデータ ファイルに対して読み書きする」を参照してください。

バッファは、データをキャッシュするために使用するメモリ内のバイトのブロックです。これによって、オペレーティング システムの呼び出しの回数が減少します。バッファは読み取りと書き込みのパフォーマンスを向上させます。バッファは読み取りまたは書き込みのいずれかのために使用できますが、同時に両方のためには使用できません。BufferedStreamRead メソッドと Write メソッドは、自動的にバッファを維持します。

BufferedStream は、特定の種類のストリームで作成できます。これにより基になるデータ ソースまたはリポジトリに対して、バイトの読み取りと書き込みが可能になります。他のデータ型の読み取りと書き込みには、BinaryReaderBinaryWriter を使用します。BufferedStream は、バッファが不要なときに、バッファによって入出力の速度が低下しないように設計されています。常に内部バッファ サイズより大きいサイズの読み取りと書き込みを行う場合、BufferedStream は、内部バッファさえも割り当てないことがあります。BufferedStream は共有バッファにも読み取りと書き込みを格納します。ほとんどの場合、常に一連の読み取りまたは書き込みの操作を実行し、めったにこの 2 つの操作が切り替わらないことを前提にしています。

次に示すのは、特定の I/O 操作のパフォーマンスを向上させるために、BufferedStream クラスを NetworkStream クラス上で使用するコード例です。この例では、クライアントを起動する前にリモート コンピュータのサーバーを起動する必要があります。また、クライアントを起動するときには、コマンド ライン引数としてリモート コンピュータ名を指定します。dataArraySize 定数と streamBufferSize 定数にさまざまな値を使用することで、パフォーマンスへの影響を確認できます。

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;
        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 ? "faster" : "slower");
    }
}

import System.*;
import System.IO.*;
import System.Globalization.*;
import System.Net.*;
import System.Net.Sockets.*;

public class Client
{
    private static int dataArraySize = 100;
    private static int streamBufferSize = 1000;
    private static int numberOfLoops = 10000;

    public 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).get_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.

        Stream netStream = new NetworkStream(clientSocket, true);
        Stream bufStream = new BufferedStream(netStream, streamBufferSize);
        try {
            try {
                // Check whether the underlying stream supports seeking.
                Console.WriteLine("NetworkStream {0} seeking.\n",
                    (bufStream.get_CanSeek())? "supports" : "does not support");
                // Send and receive data.
                if ( bufStream.get_CanWrite()  ) {
                    SendData(netStream, bufStream);
                }
                if ( bufStream.get_CanRead()  ) {
                    ReceiveData(netStream, bufStream);
                }

                // When execution exits the using statement, netStream
                // is disposed, which in turn shuts down the connection 
                // and closes clientSocket.
                Console.WriteLine("\nShutting down the connection.");
            }
            finally {
                netStream.Dispose();
            }
        }
        finally {
            bufStream.Dispose();
        }         
    } //main   
   
    static void SendData(Stream netStream, Stream bufStream) 
    {
        DateTime startTime;
        double networkTime,bufferedTime;

        // Create random data to send to the server.        
        ubyte dataToSend[] = new ubyte[dataArraySize];
        new Random().NextBytes(dataToSend);

        // Send the data using the NetworkStream.
        Console.WriteLine("Sending data using NetworkStream.");
        startTime = DateTime.get_Now();
        for(int i=0;i < numberOfLoops;i++) {
            netStream.Write(dataToSend, 0, dataToSend.length);
        }        
        networkTime =
            ((DateTime.get_Now()).Subtract(startTime)).get_TotalSeconds();
        Console.WriteLine("{0} bytes sent in {1} seconds.\n",
            System.Convert.ToString(numberOfLoops * dataToSend.length),
            ((System.Double) networkTime).ToString("F1"));

        // Send the data using the BufferedStream.
        Console.WriteLine("Sending data using BufferedStream.");
        startTime = DateTime.get_Now();
        for(int i=0;i < numberOfLoops;i++) {
            bufStream.Write(dataToSend, 0, dataToSend.length);
        }        
        bufStream.Flush();
        bufferedTime = 
            ((DateTime.get_Now()).Subtract(startTime)).get_TotalSeconds();
        Console.WriteLine("{0} bytes sent in {1} seconds.\n",
            System.Convert.ToString (numberOfLoops * dataToSend.length),
            ((System.Double)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",
            ((System.Double)(networkTime / bufferedTime)).ToString("P0"),
            (bufferedTime < networkTime) ? "faster" : "slower");
    } //SendData
   
    static void ReceiveData(Stream netStream, Stream bufStream) 
    {
        DateTime startTime;
        double bufferedTime = 0;
        double networkTime;
        int bytesReceived = 0;
        ubyte receivedData[] = new ubyte[dataArraySize];

        // Receive data using the NetworkStream.
        Console.WriteLine("Receiving data using NetworkStream.");
        startTime = DateTime.get_Now();
        while((bytesReceived < numberOfLoops * receivedData.length)) {
            bytesReceived += netStream.Read(receivedData,0,receivedData.length);
        }
        networkTime = 
            ((DateTime.get_Now()).Subtract(startTime)).get_TotalSeconds();
        Console.WriteLine("{0} bytes received in {1} seconds.\n",
            (new Integer(bytesReceived)).ToString(),
            ((System.Double)networkTime).ToString("F1"));

        // Receive data using the BufferedStream.
        Console.WriteLine("Receiving data using BufferedStream.");
        bytesReceived = 0;
        startTime = DateTime.get_Now();
        while((bytesReceived < numberOfLoops * receivedData.length)) {
            bytesReceived += bufStream.Read(receivedData,0,receivedData.length);
        }
        bufferedTime =
            ((DateTime.get_Now()).Subtract(startTime)).get_TotalSeconds();
        Console.WriteLine("{0} bytes received in {1} seconds.\n",
            (new Integer(bytesReceived)).ToString(),
            ((System.Double) 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.",
            ((System.Double)(networkTime / bufferedTime)).ToString("P0"),
            (bufferedTime < networkTime) ? "faster" : "slower");
    } //ReceiveData
} //Client

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

System.Object
   System.MarshalByRefObject
     System.IO.Stream
      System.IO.BufferedStream

この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバの場合は、スレッド セーフであるとは限りません。

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。

.NET Framework

サポート対象 : 2.0、1.1、1.0

コミュニティの追加

追加
表示:
© 2014 Microsoft