NetworkStream Classe
Definição
Fornece o fluxo de dados subjacente para acesso à rede.Provides the underlying stream of data for network access.
public ref class NetworkStream : System::IO::Stream
public class NetworkStream : System.IO.Stream
type NetworkStream = class
inherit Stream
type NetworkStream = class
inherit Stream
interface IDisposable
Public Class NetworkStream
Inherits Stream
- Herança
- Herança
- Implementações
Exemplos
O exemplo de código a seguir demonstra como criar um NetworkStream de um conectado Stream Socket e executar e/s de bloqueio síncrono básico.The following code example demonstrates how to create a NetworkStream from a connected StreamSocket and perform basic synchronous blocking I/O.
// Examples for constructors that do not specify file permission.
// Create the NetworkStream for communicating with the remote host.
NetworkStream^ myNetworkStream;
if ( networkStreamOwnsSocket )
{
myNetworkStream = gcnew NetworkStream( mySocket,true );
}
else
{
myNetworkStream = gcnew NetworkStream( mySocket );
}
// Examples for constructors that do not specify file permission.
// Create the NetworkStream for communicating with the remote host.
NetworkStream myNetworkStream;
if (networkStreamOwnsSocket){
myNetworkStream = new NetworkStream(mySocket, true);
}
else{
myNetworkStream = new NetworkStream(mySocket);
}
' Examples for constructors that do not specify file permission.
' Create the NetworkStream for communicating with the remote host.
Dim myNetworkStream As NetworkStream
If networkStreamOwnsSocket Then
myNetworkStream = New NetworkStream(mySocket, True)
Else
myNetworkStream = New NetworkStream(mySocket)
End If
Comentários
A NetworkStream classe fornece métodos para enviar e receber dados sobre Stream soquetes no modo de bloqueio.The NetworkStream class provides methods for sending and receiving data over Stream sockets in blocking mode. Para obter mais informações sobre como bloquear e não bloquear Socket s, consulte usando um soquete de cliente assíncrono.For more information about blocking versus nonblocking Sockets, see Using an Asynchronous Client Socket. Você pode usar a NetworkStream classe para transferência de dados síncrona e assíncrona.You can use the NetworkStream class for both synchronous and asynchronous data transfer. Para obter mais informações sobre comunicação assíncrona e síncrona, consulte Sockets.For more information about synchronous and asynchronous communication, see Sockets.
Para criar um NetworkStream , você deve fornecer um conectado Socket .To create a NetworkStream, you must provide a connected Socket. Você também pode especificar a FileAccess permissão que o NetworkStream tem acima do fornecido Socket .You can also specify what FileAccess permission the NetworkStream has over the provided Socket. Por padrão, fechar o não NetworkStream fecha o fornecido Socket .By default, closing the NetworkStream does not close the provided Socket. Se desejar que o NetworkStream tenha permissão para fechar o fornecido Socket , você deverá especificar true para o valor do ownsSocket parâmetro.If you want the NetworkStream to have permission to close the provided Socket, you must specify true for the value of the ownsSocket parameter.
Use os Write Read métodos e para simples e/s de bloqueio síncrono de thread único.Use the Write and Read methods for simple single thread synchronous blocking I/O. Se você quiser processar a e/s usando threads separados, considere usar os BeginWrite EndWrite métodos e, ou os BeginRead EndRead métodos e para comunicação.If you want to process your I/O using separate threads, consider using the BeginWrite and EndWrite methods, or the BeginRead and EndRead methods for communication.
O NetworkStream não oferece suporte ao acesso aleatório ao fluxo de dados de rede.The NetworkStream does not support random access to the network data stream. O valor da CanSeek propriedade, que indica se o fluxo dá suporte à busca, é sempre false ; a leitura da Position propriedade, a leitura da Length propriedade ou a chamada do Seek método gerará um NotSupportedException .The value of the CanSeek property, which indicates whether the stream supports seeking, is always false; reading the Position property, reading the Length property, or calling the Seek method will throw a NotSupportedException.
As operações de leitura e gravação podem ser executadas simultaneamente em uma instância da NetworkStream classe sem a necessidade de sincronização.Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. Desde que haja um thread exclusivo para as operações de gravação e um thread exclusivo para as operações de leitura, não haverá nenhuma interferência cruzada entre threads de leitura e gravação e nenhuma sincronização será necessária.As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.
Construtores
| NetworkStream(Socket) |
Cria uma nova instância da classe NetworkStream para o Socket especificado.Creates a new instance of the NetworkStream class for the specified Socket. |
| NetworkStream(Socket, Boolean) |
Inicializa uma nova instância da classe NetworkStream para o Socket especificado com a propriedade Socket especificada.Initializes a new instance of the NetworkStream class for the specified Socket with the specified Socket ownership. |
| NetworkStream(Socket, FileAccess) |
Cria uma nova instância da classe NetworkStream para o Socket especificado com os direitos de acesso especificados.Creates a new instance of the NetworkStream class for the specified Socket with the specified access rights. |
| NetworkStream(Socket, FileAccess, Boolean) |
Cria uma nova instância da classe NetworkStream para o Socket especificado com os direitos de acesso e a propriedade Socket especificados.Creates a new instance of the NetworkStream class for the specified Socket with the specified access rights and the specified Socket ownership. |
Propriedades
| CanRead |
Obtém um valor que indica se o NetworkStream dá suporte à leitura.Gets a value that indicates whether the NetworkStream supports reading. |
| CanSeek |
Obtém um valor que indica se o fluxo dá suporte à busca.Gets a value that indicates whether the stream supports seeking. Não há suporte para esta propriedade atualmente.This property is not currently supported. Essa propriedade sempre retorna |
| CanTimeout |
Indica se as propriedades de tempo limite são utilizáveis para NetworkStream.Indicates whether timeout properties are usable for NetworkStream. |
| CanTimeout |
Obtém um valor que determina se o fluxo atual pode atingir o tempo limite.Gets a value that determines whether the current stream can time out. (Herdado de Stream) |
| CanWrite |
Obtém um valor que indica se o NetworkStream dá suporte à gravação.Gets a value that indicates whether the NetworkStream supports writing. |
| DataAvailable |
Obtém um valor que indica se há dados disponíveis no NetworkStream a ser lido.Gets a value that indicates whether data is available on the NetworkStream to be read. |
| Length |
Obtém o tamanho dos dados disponíveis no fluxo.Gets the length of the data available on the stream. Atualmente, esta propriedade não tem suporte e sempre gera um NotSupportedException.This property is not currently supported and always throws a NotSupportedException. |
| Position |
Obtém ou define a posição atual no fluxo.Gets or sets the current position in the stream. Atualmente, esta propriedade não tem suporte e sempre gera um NotSupportedException.This property is not currently supported and always throws a NotSupportedException. |
| Readable |
Obtém ou define um valor que indica se o NetworkStream pode ser lido.Gets or sets a value that indicates whether the NetworkStream can be read. |
| ReadTimeout |
Obtém ou define a quantidade de tempo que uma operação de leitura é bloqueada aguardando dados.Gets or sets the amount of time that a read operation blocks waiting for data. |
| ReadTimeout |
Obtém ou define um valor, em milissegundos, que determina por quanto tempo o fluxo tentará realizar a leitura antes do tempo limite.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out. (Herdado de Stream) |
| Socket | |
| Writeable |
Obtém um valor que indica se o NetworkStream é gravável.Gets a value that indicates whether the NetworkStream is writable. |
| WriteTimeout |
Obtém ou define a quantidade de tempo que uma operação de gravação fica bloqueada aguardando dados.Gets or sets the amount of time that a write operation blocks waiting for data. |
| WriteTimeout |
Obtém ou define um valor, em milissegundos, que determina por quanto tempo o fluxo tentará realizar a gravação antes do tempo limite.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out. (Herdado de Stream) |
Métodos
| BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) |
Inicia uma leitura assíncrona do NetworkStream.Begins an asynchronous read from the NetworkStream. |
| BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) |
Inicia uma operação de leitura assíncrona.Begins an asynchronous read operation. (Considere o uso de ReadAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using ReadAsync(Byte[], Int32, Int32) instead.) (Herdado de Stream) |
| BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) |
Inicia uma gravação assíncrona em um fluxo.Begins an asynchronous write to a stream. |
| BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) |
Inicia uma operação de gravação assíncrona.Begins an asynchronous write operation. (Considere o uso de WriteAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using WriteAsync(Byte[], Int32, Int32) instead.) (Herdado de Stream) |
| Close() |
Fecha o NetworkStream.Closes the NetworkStream. |
| Close() |
Fecha o fluxo atual e libera todos os recursos (como soquetes e identificadores de arquivos) associados ao fluxo atual.Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Em vez de chamar esse método, verifique se o fluxo é descartado corretamente.Instead of calling this method, ensure that the stream is properly disposed. (Herdado de Stream) |
| Close(Int32) |
Fecha o NetworkStream após aguardar o tempo especificado para permitir que os dados sejam enviados.Closes the NetworkStream after waiting the specified time to allow data to be sent. |
| CopyTo(Stream) |
Lê os bytes do fluxo atual e os grava em outro fluxo.Reads the bytes from the current stream and writes them to another stream. (Herdado de Stream) |
| CopyTo(Stream, Int32) |
Lê os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado.Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. (Herdado de Stream) |
| CopyToAsync(Stream) |
Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo.Asynchronously reads the bytes from the current stream and writes them to another stream. (Herdado de Stream) |
| CopyToAsync(Stream, CancellationToken) |
Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um token de cancelamento especificado.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token. (Herdado de Stream) |
| CopyToAsync(Stream, Int32) |
Lê de maneira assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. (Herdado de Stream) |
| CopyToAsync(Stream, Int32, CancellationToken) |
Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado e um token de cancelamento.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. (Herdado de Stream) |
| CreateObjRef(Type) |
Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Herdado de MarshalByRefObject) |
| CreateWaitHandle() |
Obsoleto.
Aloca um objeto WaitHandle.Allocates a WaitHandle object. (Herdado de Stream) |
| Dispose() |
Libera todos os recursos usados pelo Stream.Releases all resources used by the Stream. (Herdado de Stream) |
| Dispose(Boolean) |
Libera os recursos não gerenciados usados pelo NetworkStream e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the NetworkStream and optionally releases the managed resources. |
| DisposeAsync() |
Libera de forma assíncrona os recursos não gerenciados usados pelo Stream.Asynchronously releases the unmanaged resources used by the Stream. (Herdado de Stream) |
| EndRead(IAsyncResult) |
Manipula o final de uma leitura assíncrona.Handles the end of an asynchronous read. |
| EndRead(IAsyncResult) |
Espera a leitura assíncrona pendente ser concluída.Waits for the pending asynchronous read to complete. (Considere o uso de ReadAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using ReadAsync(Byte[], Int32, Int32) instead.) (Herdado de Stream) |
| EndWrite(IAsyncResult) |
Manipula o final de uma gravação assíncrona.Handles the end of an asynchronous write. |
| EndWrite(IAsyncResult) |
Encerra uma operação de gravação assíncrona.Ends an asynchronous write operation. (Considere o uso de WriteAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using WriteAsync(Byte[], Int32, Int32) instead.) (Herdado de Stream) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| Finalize() |
Libera todos os recursos usados pelo NetworkStream.Releases all resources used by the NetworkStream. |
| Flush() |
Libera os dados do fluxo.Flushes data from the stream. Este método está reservado para uso futuro.This method is reserved for future use. |
| FlushAsync() |
Limpa de forma assíncrona todos os buffers nesse fluxo e faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente.Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device. (Herdado de Stream) |
| FlushAsync(CancellationToken) |
Libera os dados do fluxo como uma operação assíncrona.Flushes data from the stream as an asynchronous operation. |
| FlushAsync(CancellationToken) |
Limpa todos os buffers nesse fluxo de forma assíncrona, faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente e monitora as solicitações de cancelamento.Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. (Herdado de Stream) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetLifetimeService() |
Obsoleto.
Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| InitializeLifetimeService() |
Obsoleto.
Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| MemberwiseClone(Boolean) |
Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object. (Herdado de MarshalByRefObject) |
| ObjectInvariant() |
Obsoleto.
Oferece suporte a um Contract.Provides support for a Contract. (Herdado de Stream) |
| Read(Byte[], Int32, Int32) |
Lê dados do NetworkStream e os armazena em uma matriz de bytes.Reads data from the NetworkStream and stores it to a byte array. |
| Read(Span<Byte>) |
Lê dados do NetworkStream e os armazena em um intervalo de bytes na memória.Reads data from the NetworkStream and stores it to a span of bytes in memory. |
| Read(Span<Byte>) |
Quando for substituído em uma classe derivada, lê uma sequência de bytes do fluxo atual e avança a posição dentro do fluxo até o número de bytes lidos.When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Herdado de Stream) |
| ReadAsync(Byte[], Int32, Int32) |
Lê uma sequência de bytes do fluxo atual de forma assíncrona e avança a posição no fluxo até o número de bytes lidos.Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Herdado de Stream) |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) |
Lê dados do NetworkStream e os armazena em um intervalo especificado de uma matriz de bytes como uma operação assíncrona.Reads data from the NetworkStream and stores it to a specified range of a byte array as an asynchronous operation. |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) |
Lê de forma assíncrona uma sequência de bytes do fluxo atual, avança a posição no fluxo até o número de bytes lidos e monitora as solicitações de cancelamento.Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Herdado de Stream) |
| ReadAsync(Memory<Byte>, CancellationToken) |
Lê dados do NetworkStream e os armazena em um intervalo de memória de bytes como uma operação assíncrona.Reads data from the NetworkStream and stores it in a byte memory range as an asynchronous operation. |
| ReadAsync(Memory<Byte>, CancellationToken) |
Lê de forma assíncrona uma sequência de bytes do fluxo atual, avança a posição no fluxo até o número de bytes lidos e monitora as solicitações de cancelamento.Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Herdado de Stream) |
| ReadByte() |
Lê um byte do NetworkStream e avança a posição no fluxo em um byte ou retorna -1 caso esteja no final do fluxo.Reads a byte from the NetworkStream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. |
| ReadByte() |
Lê um byte do fluxo e avança a posição no fluxo em um byte ou retorna -1 caso esteja no final do fluxo.Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. (Herdado de Stream) |
| Seek(Int64, SeekOrigin) |
Define a posição atual do fluxo para o valor especificado.Sets the current position of the stream to the given value. Atualmente, este método não tem suporte e sempre gera um NotSupportedException.This method is not currently supported and always throws a NotSupportedException. |
| SetLength(Int64) |
Define o comprimento do fluxo.Sets the length of the stream. Esse método sempre gera um NotSupportedException.This method always throws a NotSupportedException. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
| Write(Byte[], Int32, Int32) |
Grava dados no NetworkStream de um intervalo especificado de uma matriz de bytes.Writes data to the NetworkStream from a specified range of a byte array. |
| Write(ReadOnlySpan<Byte>) |
Grava dados no NetworkStream de um intervalo de bytes somente leitura.Writes data to the NetworkStream from a read-only byte span. |
| Write(ReadOnlySpan<Byte>) |
Quando for substituído em uma classe derivada, grava uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo até o número de bytes gravados.When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Herdado de Stream) |
| WriteAsync(Byte[], Int32, Int32) |
Grava assincronamente uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo no número de bytes gravados.Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Herdado de Stream) |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) |
Grava dados no NetworkStream do intervalo especificado de uma matriz de bytes como uma operação assíncrona.Writes data to the NetworkStream from the specified range of a byte array as an asynchronous operation. |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) |
Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. (Herdado de Stream) |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) |
Grava dados no NetworkStream de um intervalo de memória de bytes de memória ROM como uma operação assíncrona.Writes data to the NetworkStream from a read-only memory byte memory range as an asynchronous operation. |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) |
Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. (Herdado de Stream) |
| WriteByte(Byte) |
Grava um byte na posição atual no NetworkStream e avança a posição dentro no fluxo em um byte.Writes a byte to the current position in the NetworkStream and advances the position within the stream by one byte. |
| WriteByte(Byte) |
Grava um byte na posição atual no fluxo e avança a posição dentro no fluxo em um byte.Writes a byte to the current position in the stream and advances the position within the stream by one byte. (Herdado de Stream) |
Implantações explícitas de interface
| IDisposable.Dispose() |
Esta API dá suporte à infraestrutura do produto e não deve ser usada diretamente do seu código. Libera todos os recursos usados pelo NetworkStream.Releases all resources used by the NetworkStream. |
| IDisposable.Dispose() |
Libera todos os recursos usados pelo Stream.Releases all resources used by the Stream. (Herdado de Stream) |
Métodos de Extensão
| ConfigureAwait(IAsyncDisposable, Boolean) |
Configura como as esperas nas tarefas retornadas de um descartável assíncrono são realizadas.Configures how awaits on the tasks returned from an async disposable are performed. |