BufferedStream 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
다른 스트림에서 작업을 읽고 쓰기 위한 버퍼링 레이어를 추가합니다. 이 클래스는 상속될 수 없습니다.
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
특정 I/O 작업의 성능을 향상 하려면 클래스입니다. 클라이언트를 시작하기 전에 원격 컴퓨터에서 서버를 시작합니다. 클라이언트를 시작할 때 원격 컴퓨터 이름을 명령줄 인수로 지정합니다. dataArraySize
및 streamBufferSize
상수를 변경하여 성능에 미치는 영향을 확인합니다.
첫 번째 예제에서는 클라이언트에서 실행되는 코드를 보여 하며 두 번째 예제에서는 서버에서 실행되는 코드를 보여줍니다.
예제 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
설명
버퍼는 데이터를 캐시하는 데 사용되는 메모리의 바이트 블록이므로 운영 체제에 대한 호출 수가 줄어듭니다. 버퍼는 읽기 및 쓰기 성능을 향상시킵니다. 버퍼는 읽기 또는 쓰기에 사용할 수 있지만 동시에 사용할 수는 없습니다. 및 Write 메서드는 ReadBufferedStream
버퍼를 자동으로 유지 관리합니다.
중요
이 형식이 구현 하는 IDisposable 인터페이스입니다. 형식을 사용 하 여 마쳤으면 직접 또는 간접적으로의 삭제 해야 있습니다. 직접 형식의 dispose 호출 해당 Dispose 의 메서드를 try
/catch
블록입니다. 삭제 하지 직접, 언어 구문 같은 사용 using
(C#에서) 또는 Using
(Visual Basic에서는). 자세한 내용은 "를 사용 하는 개체는 구현 IDisposable" 섹션을 참조 하세요.를 IDisposable 인터페이스 항목입니다.
BufferedStream
는 특정 유형의 스트림을 중심으로 구성할 수 있습니다. 기본 데이터 원본 또는 리포지토리에 바이트를 읽고 쓰기 위한 구현을 제공합니다. 및 BinaryWriter 를 사용하여 BinaryReader 다른 데이터 형식을 읽고 작성합니다. 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() |
원본 스트림에서 바이트를 읽고 |
ReadExactly(Byte[], Int32, Int32) |
|
ReadExactly(Span<Byte>) |
현재 스트림에서 바이트를 읽고 가 채워질 때까지 |
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken) |
현재 스트림에서 바이트 수를 비동기적으로 읽고 |
ReadExactlyAsync(Memory<Byte>, CancellationToken) |
현재 스트림에서 바이트를 비동기적으로 읽고, 가 채워질 때까지 |
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) |
비동기 일회용에서 반환되는 작업을 대기하는 방법을 구성합니다. |
적용 대상
추가 정보
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기