TcpListener 클래스

정의

TCP 네트워크 클라이언트에서 연결을 수신합니다.

public ref class TcpListener
public ref class TcpListener : IDisposable
public class TcpListener
public class TcpListener : IDisposable
type TcpListener = class
type TcpListener = class
    interface IDisposable
Public Class TcpListener
Public Class TcpListener
Implements IDisposable
상속
TcpListener
구현

예제

다음 코드 예제에서는 를 TcpListener만듭니다.

#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;
using namespace System::Threading;
void main()
{
   try
   {
      
      // Set the TcpListener on port 13000.
      Int32 port = 13000;
      IPAddress^ localAddr = IPAddress::Parse( "127.0.0.1" );
      
      // TcpListener* server = new TcpListener(port);
      TcpListener^ server = gcnew TcpListener( localAddr,port );
      
      // Start listening for client requests.
      server->Start();
      
      // Buffer for reading data
      array<Byte>^bytes = gcnew array<Byte>(256);
      String^ data = nullptr;
      
      // Enter the listening loop.
      while ( true )
      {
         Console::Write( "Waiting for a connection... " );
         
         // Perform a blocking call to accept requests.
         // You could also use server.AcceptSocket() here.
         TcpClient^ client = server->AcceptTcpClient();
         Console::WriteLine( "Connected!" );
         data = nullptr;
         
         // Get a stream Object* for reading and writing
         NetworkStream^ stream = client->GetStream();
         Int32 i;
         
         // Loop to receive all the data sent by the client.
         while ( i = stream->Read( bytes, 0, bytes->Length ) )
         {
            
            // Translate data bytes to a ASCII String*.
            data = Text::Encoding::ASCII->GetString( bytes, 0, i );
            Console::WriteLine( "Received: {0}", data );
            
            // Process the data sent by the client.
            data = data->ToUpper();
            array<Byte>^msg = Text::Encoding::ASCII->GetBytes( data );
            
            // Send back a response.
            stream->Write( msg, 0, msg->Length );
            Console::WriteLine( "Sent: {0}", data );
         }
         
         // Shutdown and end connection
         client->Close();
      }
   }
   catch ( SocketException^ e ) 
   {
      Console::WriteLine( "SocketException: {0}", e );
   }

   Console::WriteLine( "\nHit enter to continue..." );
   Console::Read();
}
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MyTcpListener
{
  public static void Main()
  {
    TcpListener server = null;
    try
    {
      // Set the TcpListener on port 13000.
      Int32 port = 13000;
      IPAddress localAddr = IPAddress.Parse("127.0.0.1");

      // TcpListener server = new TcpListener(port);
      server = new TcpListener(localAddr, port);

      // Start listening for client requests.
      server.Start();

      // Buffer for reading data
      Byte[] bytes = new Byte[256];
      String data = null;

      // Enter the listening loop.
      while(true)
      {
        Console.Write("Waiting for a connection... ");

        // Perform a blocking call to accept requests.
        // You could also use server.AcceptSocket() here.
        using TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("Connected!");

        data = null;

        // Get a stream object for reading and writing
        NetworkStream stream = client.GetStream();

        int i;

        // Loop to receive all the data sent by the client.
        while((i = stream.Read(bytes, 0, bytes.Length))!=0)
        {
          // Translate data bytes to a ASCII string.
          data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
          Console.WriteLine("Received: {0}", data);

          // Process the data sent by the client.
          data = data.ToUpper();

          byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

          // Send back a response.
          stream.Write(msg, 0, msg.Length);
          Console.WriteLine("Sent: {0}", data);
        }
      }
    }
    catch(SocketException e)
    {
      Console.WriteLine("SocketException: {0}", e);
    }
    finally
    {
      server.Stop();
    }

    Console.WriteLine("\nHit enter to continue...");
    Console.Read();
  }
}
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Class MyTcpListener

    Public Shared Sub Main()

    Dim server As TcpListener
    server=nothing
        Try
            ' Set the TcpListener on port 13000.
         Dim port As Int32 = 13000
         Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")

         server = New TcpListener(localAddr, port)
         
         ' Start listening for client requests.
         server.Start()
         
         ' Buffer for reading data
            Dim bytes(1024) As Byte
            Dim data As String = Nothing
         
         ' Enter the listening loop.
         While True
            Console.Write("Waiting for a connection... ")
            
            ' Perform a blocking call to accept requests.
            ' You could also use server.AcceptSocket() here.
            Dim client As TcpClient = server.AcceptTcpClient()
            Console.WriteLine("Connected!")
            
            data = Nothing
            
            ' Get a stream object for reading and writing
            Dim stream As NetworkStream = client.GetStream()
            
            Dim i As Int32
            
            ' Loop to receive all the data sent by the client.
            i = stream.Read(bytes, 0, bytes.Length)
            While (i <> 0) 
               ' Translate data bytes to a ASCII string.
               data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
                    Console.WriteLine("Received: {0}", data)
               
               ' Process the data sent by the client.
               data = data.ToUpper()
                    Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
               
               ' Send back a response.
               stream.Write(msg, 0, msg.Length)
                    Console.WriteLine("Sent: {0}", data)
              
               i = stream.Read(bytes, 0, bytes.Length)

            End While
            
            ' Shutdown and end connection
            client.Close()
         End While
      Catch e As SocketException
         Console.WriteLine("SocketException: {0}", e)
      Finally
         server.Stop()
      End Try
      
      Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
      Console.Read()
   End Sub

End Class

클라이언트 예제는 를 참조하세요 TcpClient .

설명

클래스는 TcpListener 동기 모드 차단에서 들어오는 연결 요청을 수신 대기하고 수락하는 간단한 메서드를 제공합니다. 또는 Socket 를 사용하여 에 TcpClient 연결할 TcpListener수 있습니다. TcpListener, 로컬 IP 주소 및 포트 번호 또는 포트 번호만 사용하여 IPEndPoint을 Create. 기본 서비스 공급자가 해당 값을 할당하도록 하려면 로컬 IP 주소 및 로컬 포트 번호에 0을 지정 Any 합니다. 이 작업을 수행하도록 선택하는 경우 소켓이 LocalEndpoint 연결된 후 속성을 사용하여 할당된 정보를 식별할 수 있습니다.

메서드를 Start 사용하여 들어오는 연결 요청 수신 대기를 시작합니다. Start 는 메서드를 호출하거나 큐에 Stop 대기할 때까지 들어오는 연결을 큐에 대기합니다 MaxConnections. AcceptSocket 또는 AcceptTcpClient 를 사용하여 들어오는 연결 요청 큐에서 연결을 가져옵니다. 이러한 두 메서드는 차단됩니다. 차단을 방지하려면 먼저 메서드를 Pending 사용하여 큐에서 연결 요청을 사용할 수 있는지 확인할 수 있습니다.

메서드를 Stop 호출하여 를 닫습니다 TcpListener.

참고

메서드는 Stop 허용되는 연결을 닫지 않습니다. 이러한 항목을 별도로 닫을 책임이 있습니다.

생성자

TcpListener(Int32)
사용되지 않음.
사용되지 않음.
사용되지 않음.
사용되지 않음.

지정된 포트에서 수신하는 TcpListener 클래스의 새 인스턴스를 초기화합니다.

TcpListener(IPAddress, Int32)

지정된 로컬 IP 주소와 포트 번호에서 들어오는 연결 시도를 수신하는 TcpListener 클래스의 새 인스턴스를 초기화합니다.

TcpListener(IPEndPoint)

지정된 로컬 엔드포인트를 사용하여 TcpListener 클래스의 새 인스턴스를 초기화합니다.

속성

Active

TcpListener가 클라이언트 연결을 실제로 수신하고 있는지 여부를 나타내는 값을 가져옵니다.

ExclusiveAddressUse

Boolean가 특정 포트를 하나의 내부 소켓에서만 수신하는 것을 허용하는지 여부를 지정하는 TcpListener 값을 가져오거나 설정합니다.

LocalEndpoint

현재 EndPoint의 내부 TcpListener를 가져옵니다.

Server

내부 네트워크 Socket을 가져옵니다.

메서드

AcceptSocket()

보류 중인 연결 요청을 받아들입니다.

AcceptSocketAsync()

보류 중인 연결 요청을 비동기 작업으로 허용합니다.

AcceptSocketAsync(CancellationToken)

보류 중인 연결 요청을 취소 가능한 비동기 작업으로 허용합니다.

AcceptTcpClient()

보류 중인 연결 요청을 받아들입니다.

AcceptTcpClientAsync()

보류 중인 연결 요청을 비동기 작업으로 허용합니다.

AcceptTcpClientAsync(CancellationToken)

보류 중인 연결 요청을 취소 가능한 비동기 작업으로 허용합니다.

AllowNatTraversal(Boolean)

TcpListener 인스턴스에 대해 NAT(Network Address Translation) 통과를 설정하거나 해제합니다.

BeginAcceptSocket(AsyncCallback, Object)

들어오는 연결 시도를 받아들이는 비동기 작업을 시작합니다.

BeginAcceptTcpClient(AsyncCallback, Object)

들어오는 연결 시도를 받아들이는 비동기 작업을 시작합니다.

Create(Int32)

지정된 포트에서 수신 대기할 새 TcpListener 인스턴스를 만듭니다.

Dispose()

현재 TcpListener 인스턴스에서 사용하는 모든 리소스를 해제합니다.

EndAcceptSocket(IAsyncResult)

들어오는 연결 시도를 비동기적으로 받아들이고 원격 호스트 통신을 처리할 새로운 Socket을 만듭니다.

EndAcceptTcpClient(IAsyncResult)

들어오는 연결 시도를 비동기적으로 받아들이고 원격 호스트 통신을 처리할 새로운 TcpClient을 만듭니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
Finalize()

TcpListener 클래스에서 사용한 리소스를 해제합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
Pending()

보류 중인 연결 요청이 있는지 여부를 확인합니다.

Start()

들어오는 연결 요청의 수신을 시작합니다.

Start(Int32)

최대 보류 연결 수로 들어오는 연결 요청에 대한 수신을 시작합니다.

Stop()

수신기를 닫습니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보