System.IO.BufferedStream 类

方法描述

将缓冲层添加到另一个流上的读取和写入操作。 此类不能被继承。

语法定义(C# System.IO.BufferedStream 类 的用法)

[ComVisibleAttribute(true)]
public sealed class BufferedStream : Stream

构造函数

构造函数名称 构造函数描述
BufferedStream(Stream) 使用默认的缓冲区大小 4096 字节初始化 BufferedStream 类的新实例。
BufferedStream(Stream, Int32) 使用指定的缓冲区大小初始化 BufferedStream 类的新实例。

成员/方法

方法名称 方法描述
BeginRead 开始异步读操作。 (继承自 Stream。)
BeginWrite 开始异步写操作。 (继承自 Stream。)
Close 关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)。 (继承自 Stream。)
CopyTo(Stream) 从当前流中读取字节并将其写入到目标流中。 (继承自 Stream。)
CopyTo(Stream, Int32) 从当前流中读取所有字节并将其写入到目标流中(使用指定的缓冲区大小)。 (继承自 Stream。)
CreateObjRef 创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。 (继承自 MarshalByRefObject。)
CreateWaitHandle 已过时。分配 WaitHandle 对象。 (继承自 Stream。)
Dispose() 释放由 Stream 占用的所有资源。 (继承自 Stream。)
Dispose(Boolean) 释放由 Stream 占用的非托管资源,还可以另外再释放托管资源。 (继承自 Stream。)
EndRead 等待挂起的异步读取完成。 (继承自 Stream。)
EndWrite 结束异步写操作。 (继承自 Stream。)
Equals(Object) 确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
Flush 清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中。 (重写 Stream.Flush()。)
GetHashCode 用作特定类型的哈希函数。 (继承自 Object。)
GetLifetimeService 检索控制此实例的生存期策略的当前生存期服务对象。 (继承自 MarshalByRefObject。)
GetType 获取当前实例的 Type。 (继承自 Object。)
InitializeLifetimeService 获取控制此实例的生存期策略的生存期服务对象。 (继承自 MarshalByRefObject。)
MemberwiseClone() 创建当前 Object 的浅表副本。 (继承自 Object。)
MemberwiseClone(Boolean) 创建当前 MarshalByRefObject 对象的浅表副本。 (继承自 MarshalByRefObject。)
ObjectInvariant 基础结构。提供对 Contract 的支持。 (继承自 Stream。)
Read 将字节从当前缓冲流复制到数组。 (重写 Stream.Read(Byte[], Int32, Int32)。)
ReadByte 从基础流中读取一个字节,并返回转换为 int 的该字节;或者如果从流的末尾读取则返回 -1。 (重写 Stream.ReadByte()。)
Seek 设置当前缓冲流中的位置。 (重写 Stream.Seek(Int64, SeekOrigin)。)
SetLength 设置缓冲流的长度。 (重写 Stream.SetLength(Int64)。)
ToString 返回表示当前对象的字符串。 (继承自 Object。)
Write 将字节复制到缓冲流,并将缓冲流内的当前位置前进写入的字节数。 (重写 Stream.Write(Byte[], Int32, Int32)。)
WriteByte 将一个字节写入缓冲流的当前位置。 (重写 Stream.WriteByte(Byte)。)

提示和注释

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

BufferedStream 可写在某些类型的流周围。 它提供从基础数据源或储存库读取字节以及将字节写入基础数据源或储存库的实现。 使用 BinaryReader 和 BinaryWriter 读取和写入其他数据类型。 BufferedStream 用于在不需要缓冲区时防止缓冲区降低输入和输出速度。 如果您读取和写入的大小始终大于内部缓冲区的大小,那么 BufferedStream 可能甚至无法分配内部缓冲区。 BufferedStream 也在共享缓冲区中缓冲读取和写入。 假设您几乎始终执行一系列读取或写入操作,而很少在读取和写入之间切换。

System.IO.BufferedStream 类例子

VB 复制 ' Compile using /r:System.dll. Imports Microsoft.VisualBasic Imports System 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 C# 复制 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"); } } C++ 复制 #using 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^receivedData = gcnew array(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^dataToSend = gcnew array(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(); } } VB 复制 ' Compile using /r:System.dll. Imports Microsoft.VisualBasic Imports System 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 C# 复制 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(); } } } C++ 复制 #using 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^receivedData = gcnew array(2000000); // Create random data to send to the client. array^dataToSend = gcnew array(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 

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^receivedData = gcnew array(2000000);

   // Create random data to send to the client.
   array^dataToSend = gcnew array(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();
   }

}

继承层次结构

System.Object

System.MarshalByRefObject

System.IO.Stream

System.IO.BufferedStream

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

线程安全

此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。