System.Net.Sockets.NetworkStream Class

Assembly: System.dll
Namespace: System.Net.Sockets
Summary
Provides the underlying stream of data for network access.
C# Syntax:
public class NetworkStream : Stream
Remarks
NetworkStream implements the standard .NET Framework stream mechanism to send and receive data through network sockets. NetworkStream supports both synchronous and asynchronous access to the network data stream.

NetworkStream does not support random access to the network data stream. The NetworkStream.CanSeek property is always false; reading the NetworkStream.Position property or calling the NetworkStream.Seek method will throw a NotSupportedException.

See also:
System.Net.Sockets Namespace

System.Net.Sockets.NetworkStream Member List:

Public Constructors
ctor #1 Overloaded:
.ctor(Socket socket)

Creates a new instance of the NetworkStream class for the specified Socket.
ctor #2 Overloaded:
.ctor(Socket socket, bool ownsSocket)

Initializes a new instance of the NetworkStream class for the specified socket with the specified Socket ownership.
ctor #3 Overloaded:
.ctor(Socket socket, FileAccess access)

Creates a new instance of the NetworkStream class for the specified Socket with the specified access rights.
ctor #4 Overloaded:
.ctor(Socket socket, FileAccess access, bool ownsSocket)

Creates a new instance of the NetworkStream class for the specified Socket with the specified access rights and the specified Socket ownership.
Public Properties
CanRead Read-only

Overridden:
Gets a value indicating whether the current stream supports reading.
CanSeek Read-only

Overridden:
Gets a value indicating whether the stream supports seeking. This property always returns false.
CanWrite Read-only

Overridden:
Gets a value that indicates whether the current stream supports writing.
DataAvailable Read-only

Gets a value indicating whether data is available on the stream to be read.
Length Read-only

Overridden:
The length of the data available on the stream. This property always throws a NotSupportedException.
Position Read-write

Overridden:
Gets or sets the current position in the stream. This property always throws a NotSupportedException.
Public Methods
BeginRead Overridden:
Begins an asynchronous read from a stream.
BeginWrite Overridden:
Begins an asynchronous write to a stream.
Close Overridden:
Closes the stream and optionally closes the underlying socket.
CreateObjRef
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.CreateObjRef


Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
EndRead Overridden:
Handles the end of an asynchronous read.
EndWrite Overridden:
Handles the end of an asynchronous write.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
Flush Overridden:
Flushes data from the stream. This method is reserved for future use.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.GetLifetimeService


Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
InitializeLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.InitializeLifetimeService


Obtains a lifetime service object to control the lifetime policy for this instance.
Read Overridden:
Reads data from the stream.
ReadByte
(inherited from System.IO.Stream)
See base class member description: System.IO.Stream.ReadByte


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.
Seek Overridden:
Sets the current position of the stream to the given value. This method always throws a NotSupportedException.
SetLength Overridden:
Sets the length of the stream. This method always throws a NotSupportedException.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Write Overridden:
Writes data to the stream.
WriteByte
(inherited from System.IO.Stream)
See base class member description: System.IO.Stream.WriteByte


Writes a byte to the current position in the stream and advances the position within the stream by one byte.
Protected Properties
Readable Read-write

Gets or sets a value indicating that the stream can be read.
Socket Read-only

Gets the underlying network connection.
Writeable Read-write

Gets a value that indicates whether the stream is writable.
Protected Methods
CreateWaitHandle
(inherited from System.IO.Stream)
See base class member description: System.IO.Stream.CreateWaitHandle


Allocates a WaitHandle object.
Dispose Cleans up a network stream.
Finalize Overridden:
Frees resources used by the NetworkStream.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Net.Sockets.NetworkStream Member Details

Overloaded ctor #1
Summary
Creates a new instance of the NetworkStream class for the specified Socket.
C# Syntax:
public NetworkStream(
   Socket socket
);
Parameters:

socket

The Socket that provides the network data for the new NetworkStream.

Exceptions
Exception Type Condition
ArgumentNullException socket is null.
ArgumentException socket is not connected

-or-

The Socket.SocketType property of socket is not SocketType.Stream.

IOException socket is a nonblocking socket.
Remarks
The NetworkStream is created with read/write access to the specified socket. The NetworkStream does not own the underlying socket, so calling the NetworkStream.Close method will not close the socket.
See also:
MSDN: usingstreamsonnetwork

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the NetworkStream class for the specified socket with the specified Socket ownership.
C# Syntax:
public NetworkStream(
   Socket socket,
   bool ownsSocket
);
Parameters:

socket

The network socket that the new NetworkStream will encapsulate.

ownsSocket

true if the socket will be owned by this NetworkStream instance; otherwise, false.

Exceptions
Exception Type Condition
ArgumentNullException socket is null.
ArgumentException socket is not connected

-or-

The Socket.SocketType property of socket is not SocketType.Stream.

IOException socket is a nonblocking socket.
Remarks
The NetworkStream is created with read/write access to the specified socket. If ownsSocket is true, the NetworkStream owns the underlying socket, and calling NetworkStream.Close will also close the underlying socket.

Return to top


Overloaded ctor #3
Summary
Creates a new instance of the NetworkStream class for the specified Socket with the specified access rights.
C# Syntax:
public NetworkStream(
   Socket socket,
   FileAccess access
);
Parameters:

socket

The Socket that provides the network data.

access

One of the FileAccess values that sets the NetworkStream.CanRead and NetworkStream.CanWrite properties of the NetworkStream.

Exceptions
Exception Type Condition
ArgumentNullException socket is null.
ArgumentException socket is not connected

-or-

The Socket.SocketType property of socket is not SocketType.Stream.

IOException socket is a nonblocking socket.
Remarks
The NetworkStream is created with the specified access to the specified socket. The NetworkStream does not own the underlying socket, so calling the NetworkStream.Close method will not close the socket.

Return to top


Overloaded ctor #4
Summary
Creates a new instance of the NetworkStream class for the specified Socket with the specified access rights and the specified Socket ownership.
C# Syntax:
public NetworkStream(
   Socket socket,
   FileAccess access,
   bool ownsSocket
);
Parameters:

socket

The Socket that provides the network data.

access

One of the FileAccess values that sets the NetworkStream.CanRead and NetworkStream.CanWrite properties of the NetworkStream.

ownsSocket

true if the socket will be owned by this NetworkStream instance; otherwise, false.

Exceptions
Exception Type Condition
ArgumentNullException socket is null.
ArgumentException socket is not connected

-or-

The Socket.SocketType property of socket is not SocketType.Stream.

IOException socket is a nonblocking socket.
Remarks
The NetworkStream is created with the specifed access to the specified socket. If ownsSocket is true, the NetworkStream owns the underlying socket, and calling NetworkStream.Close will also close the underlying socket.

Return to top


Overridden Property: CanRead (read-only)
Summary
Gets a value indicating whether the current stream supports reading.
C# Syntax:
public override bool CanRead {get;}

Return to top


Overridden Property: CanSeek (read-only)
Summary
Gets a value indicating whether the stream supports seeking. This property always returns false.
C# Syntax:
public override bool CanSeek {get;}

Return to top


Overridden Property: CanWrite (read-only)
Summary
Gets a value that indicates whether the current stream supports writing.
C# Syntax:
public override bool CanWrite {get;}

Return to top


Property: DataAvailable (read-only)
Summary
Gets a value indicating whether data is available on the stream to be read.
C# Syntax:
public virtual bool DataAvailable {get;}

Return to top


Overridden Property: Length (read-only)
Summary
The length of the data available on the stream. This property always throws a NotSupportedException.
C# Syntax:
public override long Length {get;}
Exceptions
Exception Type Condition
NotSupportedException Any access.

Return to top


Overridden Property: Position (read-write)
Summary
Gets or sets the current position in the stream. This property always throws a NotSupportedException.
C# Syntax:
public override long Position {get; set;}
Exceptions
Exception Type Condition
NotSupportedException Any access.

Return to top


Property: Readable (read-write)
Summary
Gets or sets a value indicating that the stream can be read.
C# Syntax:
protected bool Readable {get; set;}
Remarks
The NetworkStream.Readable property is accessible only through this class or a derived class. Other classes can determine whether a NetworkStream is readable by checking the NetworkStream.CanRead property.

The NetworkStream.Readable property is set when the NetworkStream is initialized.

Return to top


Property: Socket (read-only)
Summary
Gets the underlying network connection.
C# Syntax:
protected Socket Socket {get;}
Remarks
The NetworkStream.Socket property represents the underlying network socket that this NetworkStream encapsulates.

The NetworkStream.Socket property is set when the NetworkStream is initialized.

Return to top


Property: Writeable (read-write)
Summary
Gets a value that indicates whether the stream is writable.
C# Syntax:
protected bool Writeable {get; set;}
Remarks
The NetworkStream.Writeable property is accessible only through this class or a derived class. Other classes can determine whether a NetworkStream is writable by checking the NetworkStream.CanWrite property.

The NetworkStream.Writeable property is set when the NetworkStream is initialized.

Return to top


Overridden Method: BeginRead(
   byte[] buffer,
   int offset,
   int size,
   AsyncCallback callback,
   object state
)
Summary
Begins an asynchronous read from a stream.
C# Syntax:
public override IAsyncResult BeginRead(
   byte[] buffer,
   int offset,
   int size,
   AsyncCallback callback,
   object state
);
Parameters:

buffer

The location in memory that stores the data from the stream.

offset

The location in buffer to begin storing the data to.

size

The size of buffer.

callback

The delegate to call when the asynchronous call is complete.

state

An object containing additional information supplied by the client.

Return Value:
An IAsyncResult representing the asynchronous call.
Exceptions
Exception Type Condition
ArgumentNullException buffer is null.
ArgumentException buffer is smaller than the requested number of bytes.
IOException There is a failure while reading from the network.
Remarks
The NetworkStream.BeginRead method begins an asynchronous request for data from a network stream. The method that implements the AsyncCallback delegate uses the NetworkStream.EndRead method to return the amount of data read from the stream.
See also:
NetworkStream.EndRead | MSDN: asynchronousprogramming

Return to top


Overridden Method: BeginWrite(
   byte[] buffer,
   int offset,
   int size,
   AsyncCallback callback,
   object state
)
Summary
Begins an asynchronous write to a stream.
C# Syntax:
public override IAsyncResult BeginWrite(
   byte[] buffer,
   int offset,
   int size,
   AsyncCallback callback,
   object state
);
Parameters:

buffer

The location in memory that holds the data to send.

offset

The location in buffer to begin sending the data.

size

The size of buffer.

callback

The delegate to call when the asynchronous call is complete.

state

An object containing additional information supplied by the client.

Return Value:
An IAsyncResult representing the asynchronous call.
Exceptions
Exception Type Condition
ArgumentNullException buffer is null.
ArgumentException buffer is smaller than the requested number of bytes.
IOException There is a failure while writing to the network.
Remarks
The NetworkStream.BeginWrite method begins to send data asynchronously to the network stream. The method that implements the AsyncCallback delegate uses the NetworkStream.EndRead method to complete sending the data.

Return to top


Overridden Method: Close()
Summary
Closes the stream and optionally closes the underlying socket.
C# Syntax:
public override void Close();
Remarks
The NetworkStream.Close method frees resources used by the NetworkStream instance and, if the NetworkStream owns the underlying socket, closes the underlying socket.

Return to top


Method: CreateObjRef(
   Type requestedType
)
Inherited
See base class member description: System.MarshalByRefObject.CreateObjRef

Summary
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
C# Syntax:
public virtual ObjRef CreateObjRef(
   Type requestedType
);
Parameters:

requestedType

The Type of the object that the new ObjRef will reference.

Return Value:
Information required to generate a proxy.
Exceptions
Exception Type Condition
RemotingException This instance is not a valid remoting object.

Return to top


Method: CreateWaitHandle()
Inherited
See base class member description: System.IO.Stream.CreateWaitHandle

Summary
Allocates a WaitHandle object.
C# Syntax:
protected virtual WaitHandle CreateWaitHandle();
Return Value:
A reference to the allocated WaitHandle.
Remarks
When called for the first time, the current method creates a WaitHandle object and returns it. On subsequent calls, the CreateWaitHandle returns a reference to the same wait handle.

Use this method if you implement the asynchronous methods and require a way of blocking in Stream.EndRead or Stream.EndWrite until the asynchronous operation is complete.

Return to top


Method: Dispose(
   bool disposing
)
Summary
Cleans up a network stream.
C# Syntax:
protected virtual void Dispose(
   bool disposing
);
Parameters:

disposing

true if this method was called by another method such as NetworkStream.Close or NetworkStream.Dispose; false if this method was called by the finalizer.

Return to top


Overridden Method: EndRead(
   IAsyncResult asyncResult
)
Summary
Handles the end of an asynchronous read.
C# Syntax:
public override int EndRead(
   IAsyncResult asyncResult
);
Parameters:

asyncResult

An IAsyncResult representing an asynchronous call.

Return Value:
The number of bytes read from the stream.
Exceptions
Exception Type Condition
ArgumentException asyncResult is null.
IOException An error occurs while reading the network.
Remarks
The NetworkStream.EndRead method completes an asynchronous read of the network stream started with the NetworkStream.BeginRead method.
See also:
NetworkStream.BeginRead | MSDN: asynchronousprogramming

Return to top


Overridden Method: EndWrite(
   IAsyncResult asyncResult
)
Summary
Handles the end of an asynchronous write.
C# Syntax:
public override void EndWrite(
   IAsyncResult asyncResult
);
Parameters:

asyncResult

The IAsyncResult representing the asynchronous call.

Exceptions
Exception Type Condition
ArgumentNullException asyncResult is null.
IOException An error occurs while writing to the network.
Remarks
The NetworkStream.EndWrite method completes an asynchronous write to a network stream started with the NetworkStream.BeginWrite method.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: Finalize()
Summary
Frees resources used by the NetworkStream.
C# Syntax:
~NetworkStream();
Remarks
The NetworkStream finalizer calls the NetworkStream.Close method to close the stream.

Return to top


Overridden Method: Flush()
Summary
Flushes data from the stream. This method is reserved for future use.
C# Syntax:
public override void Flush();
Remarks
The NetworkStream.Flush method implements the Stream.Flush method but, because NetworkStream is not buffered, has no effect on network streams. Calling the NetworkStream.Flush method will not throw an exception.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.GetLifetimeService

Summary
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
C# Syntax:
public object GetLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance.
Remarks
For more information about lifetime services, see the LifetimeServices class.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: InitializeLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.InitializeLifetimeService

Summary
Obtains a lifetime service object to control the lifetime policy for this instance.
C# Syntax:
public virtual object InitializeLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the LifetimeServices.LeaseManagerPollTime property.
Remarks
For more information about lifetime services, see the LifetimeServices class.
Example
The following code example demonstrates creating a lease.
 public class MyClass : MarshalByRefObject
 {
   public override Object InitializeLifetimeService()
   {
     ILease lease = (ILease)base.InitializeLifetimeService();
     if (lease.CurrentState == LeaseState.Initial)
     {
          lease.InitialLeaseTime = TimeSpan.FromMinutes(1);
          lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
           lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
     }
       return lease;
   }
 }

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: Read(
   in byte[] buffer,
   int offset,
   int size
)
Summary
Reads data from the stream.
C# Syntax:
public override int Read(
   in byte[] buffer,
   int offset,
   int size
);
Parameters:

buffer

The location in memory to store data read from the stream.

offset

The location in the buffer to begin storing the data to.

size

The number of bytes to read from the stream.

Return Value:
The number of bytes read from the stream.
Exceptions
Exception Type Condition
ArgumentNullException buffer is null.
ArgumentException buffer is smaller than the requested number of bytes.
IOException There is a failure while reading from the network.
Remarks
The NetworkStream.Read method reads data from the network stream into a data buffer.
See also:
Socket.Receive | MSDN: usingstreamsonnetwork

Return to top


Method: ReadByte()
Inherited
See base class member description: System.IO.Stream.ReadByte

Summary
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.
C# Syntax:
public virtual int ReadByte();
Return Value:
The unsigned byte cast to an Int32, or -1 if at the end of the stream.
Exceptions
Exception Type Condition
IOException The stream is closed.
NotSupportedException The stream does not support reading.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
Use the Stream.CanRead property to determine whether the current instance supports reading.

Attempts to manipulate the stream after the stream has been closed could throw an ObjectDisposedException.



Notes to implementors: The default implementation on Stream creates a new single-byte array and then calls Stream.Read. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.

Return to top


Overridden Method: Seek(
   long offset,
   SeekOrigin origin
)
Summary
Sets the current position of the stream to the given value. This method always throws a NotSupportedException.
C# Syntax:
public override long Seek(long offset, Seek(
   long offset,
   SeekOrigin origin
);
Parameters:

offset

This parameter is not used.

origin

This parameter is not used.

Return Value:
The position in the stream. This method is not supported.
Exceptions
Exception Type Condition
NotSupportedException Any access.

Return to top


Overridden Method: SetLength(
   long value
)
Summary
Sets the length of the stream. This method always throws a NotSupportedException.
C# Syntax:
public override void SetLength(
   long value
);
Parameters:

value

This parameter is not used.

Exceptions
Exception Type Condition
NotSupportedException Any access.

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: Write(
   byte[] buffer,
   int offset,
   int size
)
Summary
Writes data to the stream.
C# Syntax:
public override void Write(
   byte[] buffer,
   int offset,
   int size
);
Parameters:

buffer

The data to write to the stream.

offset

The location in the buffer to start writing data from.

size

The number of bytes to write to the stream.

Exceptions
Exception Type Condition
ArgumentNullException buffer is null.
ArgumentException buffer is smaller than the requested number of bytes.
IOException There is a failure while writing to the network.
Remarks
The NetworkStream.Write method sends the contents of a data buffer to the network.

Return to top


Method: WriteByte(
   byte value
)
Inherited
See base class member description: System.IO.Stream.WriteByte

Summary
Writes a byte to the current position in the stream and advances the position within the stream by one byte.
C# Syntax:
public virtual void WriteByte(
   byte value
);
Parameters:

value

The byte to write to the stream.

Exceptions
Exception Type Condition
IOException The stream is closed.
NotSupportedException The stream does not support writing, or the stream is already closed.
ObjectDisposedException Methods were called after the stream was closed.
Remarks
Use the Stream.CanWrite property to determine whether the current instance supports writing.

Notes to implementors: The default implementation on Stream creates a new single-byte array and then calls Stream.Write. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.