Export (0) Print
Expand All

TcpClient.GetStream Method

Returns the NetworkStream used to send and receive data.

[Visual Basic]
Public Function GetStream() As NetworkStream
[C#]
public NetworkStream GetStream();
[C++]
public: NetworkStream* GetStream();
[JScript]
public function GetStream() : NetworkStream;

Return Value

The underlying NetworkStream.

Exceptions

Exception Type Condition
InvalidOperationException The TcpClient is not connected to a remote host.
ObjectDisposedException The TcpClient has been closed.

Remarks

GetStream returns a NetworkStream that you can use to send and receive data. The NetworkStream class inherits from the Stream class, which provides a rich collection of methods and properties used to facilitate network communications.

You must call the Connect method first, or the GetStream method will throw an InvalidOperationException. Once you have obtained the NetworkStream, call the Write method to send data to the remote host. Call the Read method to receive data arriving from the remote host. Both of these methods block until the specified operation is performed. You can avoid blocking on a read operation by checking the DataAvailable property. A true value means that data has arrived from the remote host and is available for reading. In this case, Read is guaranteed to complete immediately. If the remote host has shutdown its connection, Read will immediately return with zero bytes.

Note   You must close the NetworkStream when you are through sending and receiving data. Closing TcpClient does not release the NetworkStream.
Note   If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. Once you have obtained this code, you can refer to the Windows Socket Version 2 API error code documentation in MSDN for a detailed description of the error.

Example

[Visual Basic, C#, C++] The following example uses GetStream to obtain the underlying NetworkStream. After obtaining the NetworkStream, it sends and receives using its Write and Read methods.

[Visual Basic] 
Dim tcpClient As New TcpClient()
' Uses the GetStream public method to return the NetworkStream.

   Dim netStream As NetworkStream = tcpClient.GetStream()
   If netStream.CanWrite Then
      Dim sendBytes As [Byte]() = Encoding.UTF8.GetBytes("Is anybody there?")
      netStream.Write(sendBytes, 0, sendBytes.Length)
   Else
      Console.WriteLine("You cannot write data to this stream.")
      tcpClient.Close()
      ' Closing the tcpClient instance does not close the network stream.
      netStream.Close()
      Return
   End If
   If netStream.CanRead Then
      
      ' Reads the NetworkStream into a byte buffer.
      Dim bytes(tcpClient.ReceiveBufferSize) As Byte
      ' Read can return anything from 0 to numBytesToRead. 
      ' This method blocks until at least one byte is read.
      netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
      
      ' Returns the data received from the host to the console.
      Dim returndata As String = Encoding.ASCII.GetString(bytes)
      Console.WriteLine(("This is what the host returned to you: " + returndata))
   Else
      Console.WriteLine("You cannot read data from this stream.")
      tcpClient.Close()
      ' Closing the tcpClient instance does not close the network stream.
      netStream.Close()
      Return
   End If
 

[C#] 
TcpClient tcpClient = new TcpClient ();

// Uses the GetStream public method to return the NetworkStream.
NetworkStream netStream = tcpClient.GetStream ();

if (netStream.CanWrite)
{
    Byte[] sendBytes = Encoding.UTF8.GetBytes ("Is anybody there?");
    netStream.Write (sendBytes, 0, sendBytes.Length);
}
else
{
    Console.WriteLine ("You cannot write data to this stream.");
    tcpClient.Close ();

    // Closing the tcpClient instance does not close the network stream.
    netStream.Close ();
    return;
}

if (netStream.CanRead)
{
    // Reads NetworkStream into a byte buffer.
    byte[] bytes = new byte[tcpClient.ReceiveBufferSize];

    // Read can return anything from 0 to numBytesToRead. 
    // This method blocks until at least one byte is read.
    netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize);

    // Returns the data received from the host to the console.
    string returndata = Encoding.UTF8.GetString (bytes);

    Console.WriteLine ("This is what the host returned to you: " + returndata);
}
else
{
    Console.WriteLine ("You cannot read data from this stream.");
    tcpClient.Close ();

    // Closing the tcpClient instance does not close the network stream.
    netStream.Close ();
    return;
}


[C++] 
TcpClient* tcpClient = new TcpClient();
// Uses the GetStream public method to return the NetworkStream.

    NetworkStream* netStream = tcpClient->GetStream();
    if(netStream->CanWrite)
    {
        Byte sendBytes[] = Encoding::UTF8->GetBytes(S"Is anybody there?");
        netStream->Write(sendBytes, 0, sendBytes->Length);
    }
    else
    {
        Console::WriteLine(S"You cannot write data to this stream.");
        tcpClient->Close();
        
        // Closing the tcpClient instance does not close the network stream.
        netStream->Close ();
        return;
    }
    if(netStream->CanRead){
     
      // Reads NetworkStream into a byte buffer.
      Byte bytes[] = new Byte[tcpClient->ReceiveBufferSize];
      // Read can return anything from 0 to numBytesToRead. 
      // This method blocks until at least one byte is read.
      netStream->Read(bytes, 0, (int) tcpClient->ReceiveBufferSize);
             
     // Returns the data received from the host to the console.
     String* returndata = Encoding::UTF8->GetString(bytes);
     Console::WriteLine(S"This is what the host returned to you: {0}", returndata);
    }
    else
    {
         Console::WriteLine(S"You cannot read data from this stream.");
         tcpClient->Close();
         
         // Closing the tcpClient instance does not close the network stream.
         netStream->Close ();
         return;
    }

  

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

See Also

TcpClient Class | TcpClient Members | System.Net.Sockets Namespace | NetworkStream | Write | Read | DataAvailable | Stream | Connect

Show:
© 2014 Microsoft