NetworkStream Class

Summary

Represents a transport-level stream of data for network communication.

The NetworkStream class provides the underlying stream for network communication. It inherits from the Stream class and implements methods for reading from and writing to a network connection.

Members Description
Properties Provides access to stream properties.
Methods Provides operations for reading, writing, and managing the stream.
Events Notification mechanisms for stream events.

Properties

CanRead

Gets a value indicating whether the current stream supports reading.

public override bool CanRead { get; }

CanSeek

Gets a value indicating whether the current stream supports seeking.

public override bool CanSeek { get; }

CanTimeout

Gets a value indicating whether the stream supports timing out.

public override bool CanTimeout { get; }

DataAvailable

Gets a value indicating whether data is available on the stream.

public bool DataAvailable { get; }

Length

Gets the length in bytes of the stream.

public override long Length { get; }

Position

Gets or sets the current position in the stream.

public override long Position { get; set; }

ReadTimeout

Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

public override int ReadTimeout { get; set; }

WriteTimeout

Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

public override int WriteTimeout { get; set; }

Methods

Close()

Releases the unmanaged resources used by the NetworkStream and closes the connection.

public override void Close();

Read(byte[] buffer, int offset, int size)

Reads data from the NetworkStream into the specified byte array.

public override int Read(byte[] buffer, int offset, int size);

Write(byte[] buffer, int offset, int size)

Writes data to the NetworkStream from the specified byte array.

public override void Write(byte[] buffer, int offset, int size);

BeginRead()

Begins an asynchronous read operation.

public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state);

EndRead()

Waits for the pending asynchronous read to complete.

public override int EndRead(IAsyncResult asyncResult);

BeginWrite()

Begins an asynchronous write operation.

public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state);

EndWrite()

Ends a pending asynchronous write operation.

public override void EndWrite(IAsyncResult asyncResult);

Events

DataAvailable Event

Raised when data is available to be read from the stream.

public event EventHandler DataAvailable;

Usage Example

The following example demonstrates how to create a simple TCP client that sends a message to a server and receives a response using NetworkStream.

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class NetworkClient
{
    public static async Task Main(string[] args)
    {
        string serverAddress = "127.0.0.1";
        int serverPort = 11000;

        try
        {
            using (TcpClient client = new TcpClient())
            {
                Console.WriteLine($"Connecting to {serverAddress}:{serverPort}...");
                await client.ConnectAsync(serverAddress, serverPort);
                Console.WriteLine("Connected.");

                using (NetworkStream stream = client.GetStream())
                {
                    // Send message
                    string messageToSend = "Hello, Server!";
                    byte[] messageBytes = Encoding.ASCII.GetBytes(messageToSend);
                    await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
                    Console.WriteLine($"Sent: {messageToSend}");

                    // Receive response
                    byte[] buffer = new byte[1024];
                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                    string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    Console.WriteLine($"Received: {response}");
                }
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine($"SocketException: {e}");
        }
        catch (Exception e)
        {
            Console.WriteLine($"Exception: {e}");
        }
        Console.WriteLine("Client finished.");
    }
}