TcpClient.GetStream 메서드

정의

데이터를 보내고 받는 데 사용되는 NetworkStream을 반환합니다.

public:
 System::Net::Sockets::NetworkStream ^ GetStream();
public System.Net.Sockets.NetworkStream GetStream ();
member this.GetStream : unit -> System.Net.Sockets.NetworkStream
Public Function GetStream () As NetworkStream

반환

내부 NetworkStream입니다.

예외

TcpClient가 원격 호스트에 연결되어 있지 않은 경우

TcpClient이 닫혔습니다.

예제

다음 코드 예제에서는 를 사용하여 GetStream 기본 NetworkStream를 가져옵니다. 를 NetworkStream가져온 후 및 Read 메서드를 사용하여 Write 를 보내고 받습니다.

TcpClient^ tcpClient = gcnew TcpClient;

// Uses the GetStream public method to return the NetworkStream.
NetworkStream^ netStream = tcpClient->GetStream();
if ( netStream->CanWrite )
{
   array<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.
   array<Byte>^bytes = gcnew array<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: {0}", 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;
}
using TcpClient tcpClient = new TcpClient();
tcpClient.ConnectAsync("contoso.com", 5000);

using NetworkStream netStream = tcpClient.GetStream();

// Send some data to the peer.
byte[] sendBuffer = Encoding.UTF8.GetBytes("Is anybody there?");
netStream.Write(sendBuffer);

// Receive some data from the peer.
byte[] receiveBuffer = new byte[1024];
int bytesReceived = netStream.Read(receiveBuffer);
string data = Encoding.UTF8.GetString(receiveBuffer.AsSpan(0, bytesReceived));

Console.WriteLine($"This is what the peer sent to you: {data}");
     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

     ' Uses the Close public method to close the network stream and socket.
     tcpClient.Close()
  End Sub

설명

메서드는 GetStream 데이터를 보내고 받는 데 사용할 수 있는 를 반환 NetworkStream 합니다. 클래스는 NetworkStream 네트워크 통신을 Stream 용이하게 하는 데 사용되는 다양한 메서드 및 속성 컬렉션을 제공하는 클래스에서 상속됩니다.

먼저 메서드를 Connect 호출해야 합니다. 그렇지 않으면 메서드가 GetStream 을 throw합니다 InvalidOperationException. 를 가져온 후 메서드를 NetworkStreamWrite 호출하여 원격 호스트에 데이터를 보냅니다. 메서드를 Read 호출하여 원격 호스트에서 도착하는 데이터를 수신합니다. 이 두 메서드는 지정된 작업이 수행될 때까지 차단됩니다. 속성을 확인하여 읽기 작업이 차단되는 것을 방지할 DataAvailable 수 있습니다. 값은 true 데이터가 원격 호스트에서 도착했으며 읽을 수 있음을 의미합니다. 이 경우 는 Read 즉시 완료되도록 보장됩니다. 원격 호스트가 연결을 종료한 경우 는 Read 즉시 0바이트로 반환됩니다.

참고

가 수신되면 를 SocketException사용하여 SocketException.ErrorCode 특정 오류 코드를 가져옵니다. 이 코드를 가져온 후에는 Windows 소켓 버전 2 API 오류 코드 설명서에서 오류에 대한 자세한 설명을 참조할 수 있습니다.

참고

애플리케이션에 네트워크 추적을 사용하도록 설정하면 이 멤버에서 추적 정보를 출력합니다. 자세한 내용은 .NET Framework 네트워크 추적을 참조하세요.

적용 대상

추가 정보