TcpListenerとは? わかりやすく解説

TcpListener クラス

TCP ネットワーク クライアントからの接続待機します。

名前空間: System.Net.Sockets
アセンブリ: System (system.dll 内)
構文構文

public class TcpListener
public ref class TcpListener
public class TcpListener
public class TcpListener
解説解説

TcpListener クラスは、同期ブロッキング モードのときに受信接続要求待機した受け取ったりする単純なメソッド提供しますTcpListener接続するには、TcpClient または Socketいずれか使用できます。IPEndPoint、ローカル IP アドレスポート番号、またはポート番号だけを使用してTcpListener作成します。基になるサービス プロバイダがこれらの値を割り当てるようにするには、ローカル IP アドレスには Any を、ローカル ポート番号には 0 を指定しますこのように指定した場合は、LocalEndpoint プロパティ使用すると、ソケット接続され後で割り当てられ情報確認できます

Start メソッド使用して受信接続要求待機開始しますStart は、Stop メソッド呼び出されるか、MaxConnections がキュー置かれるまでは、受信接続要求キュー置きます。AcceptSocket または AcceptTcpClient のいずれか使用して受信接続要求キューから接続引き出します。この 2 つメソッドブロックしますブロックしないようにする場合は、まず、Pending メソッド使用して接続要求キュー内で使用可能かどうか確認します

TcpListener閉じるには、Stop メソッド使用します

メモメモ

Stop メソッドは、受け取ったどの接続終了しません。これらの接続1 つずつ終了させる必要があります

使用例使用例

TcpListener作成するコード例次に示します

Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports Microsoft.VisualBasic


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 user 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 'Main

End Class 'MyTcpListener 
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 user server.AcceptSocket() here.
        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);            
        }
         
        // Shutdown and end connection
        client.Close();
      }
    }
    catch(SocketException e)
    {
      Console.WriteLine("SocketException: {0}", e);
    }
    finally
    {
       // Stop listening for new clients.
       server.Stop();
    }

      
    Console.WriteLine("\nHit enter to continue...");
    Console.Read();
  }   
}
#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 user 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();
}


クライアント例については、TcpClientトピック参照してください

.NET Framework のセキュリティ.NET Frameworkセキュリティ
継承階層継承階層
System.Object
  System.Net.Sockets.TcpListener
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
TcpListener メンバ
System.Net.Sockets 名前空間
TcpClient クラス

TcpListener コンストラクタ (Int32)

メモ : このコンストラクタは、互換性のために残されています。

指定したポート待機する TcpListener クラス新しインスタンス初期化します。

名前空間: System.Net.Sockets
アセンブリ: System (system.dll 内)
構文構文

<ObsoleteAttribute("This method has been deprecated. Please
 use TcpListener(IPAddress localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")>
 _
Public Sub New ( _
    port As Integer _
)
[ObsoleteAttribute("This method has been deprecated. Please use TcpListener(IPAddress
 localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
 
public TcpListener (
    int port
)
[ObsoleteAttribute(L"This method has been deprecated. Please use TcpListener(IPAddress
 localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
 
public:
TcpListener (
    int port
)
/** @attribute ObsoleteAttribute("This method has been deprecated. Please use
 TcpListener(IPAddress localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")
 */ 
public TcpListener (
    int port
)
ObsoleteAttribute("This method has been deprecated. Please use TcpListener(IPAddress
 localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")
 
public function TcpListener (
    port : int
)

パラメータ

port

受信接続試行待機するポート

例外例外
例外種類条件

ArgumentOutOfRangeException

port が MinPort と MaxPort の間の値ではありません。

解説解説
使用例使用例

ローカル ポート番号使用してTcpListener作成するコード例次に示します

'Creates an instance of the TcpListener class by providing a local port
 number.  
Dim ipAddress As IPAddress = Dns.Resolve("localhost").AddressList(0)
Try
    Dim tcpListener As New
 TcpListener(ipAddress, 13)
Catch e As Exception
   Console.WriteLine(e.ToString())
End Try
            
//Creates an instance of the TcpListener class by providing a local
 port number.  
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
try{
    TcpListener tcpListener =  new TcpListener(ipAddress, 13);
    
}
catch ( Exception e ){
    Console.WriteLine( e.ToString());
}

//Creates an instance of the TcpListener class by providing a local
 port number.  

IPAddress^ ipAddress = Dns::Resolve( "localhost" )->AddressList[ 0 ];

try
{
   TcpListener^ tcpListener = gcnew TcpListener( ipAddress,13 );
}
catch ( Exception^ e ) 
{
   Console::WriteLine( e->ToString() );
}
// Creates an instance of the TcpListener class by 
// providing a local port number.  
IPAddress ipAddress = (IPAddress)Dns.Resolve(
    "localhost").get_AddressList().get_Item(0);
try {
    TcpListener tcpListener = 
        new TcpListener(ipAddress, 13);
}
catch (System.Exception e) {
    Console.WriteLine(e.ToString());
}

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
TcpListener クラス
TcpListener メンバ
System.Net.Sockets 名前空間
Start

TcpListener コンストラクタ (IPEndPoint)

指定したローカル エンドポイント使用して、TcpListener クラス新しインスタンス初期化します。

名前空間: System.Net.Sockets
アセンブリ: System (system.dll 内)
構文構文

Public Sub New ( _
    localEP As IPEndPoint _
)
Dim localEP As IPEndPoint

Dim instance As New TcpListener(localEP)
public TcpListener (
    IPEndPoint localEP
)
public:
TcpListener (
    IPEndPoint^ localEP
)
public TcpListener (
    IPEndPoint localEP
)
public function TcpListener (
    localEP : IPEndPoint
)

パラメータ

localEP

リスナ Socketバインド先のローカル エンドポイントを表す IPEndPoint。

例外例外
例外種類条件

ArgumentNullException

localEPnull 参照 (Visual Basic では Nothing) です。

解説解説

このコンストラクタ使用すると、受信接続試行待機するローカル IP アドレスおよびポート番号指定できます。このコンストラクタ使用する前に目的ローカル IP アドレスおよびポート番号使用して IPEndPoint作成しておく必要があります。このとき、IPEndPointlocalEP パラメータとしてコンストラクタ渡します

どのローカル アドレス割り当てられていてもかまわない場合は、IPAddress.Any をアドレス パラメータとして使用して IPEndPoint作成します。すると、基になるサービス プロバイダが最も適切なローカル ネットワーク アドレス割り当てます複数ネットワーク インターフェイスがある場合は、これを使用することによってアプリケーション簡素化できることあります使用するローカル ポートについても特に指定ない場合は、ポート番号 0 を使用して IPEndPoint作成します。この場合サービス プロバイダ10245000範囲使用できるポート番号割り当てますこの方法を使用する場合、LocalEndpoint プロパティ使用することによって、既に割り当てられているローカル ネットワーク アドレスポート番号を知ることができます

Start メソッド呼び出して受信接続試行待機開始します

メモメモ

このメンバは、アプリケーションネットワーク トレース有効にされている場合トレース情報出力します詳細については、「ネットワークトレース」を参照してください

使用例使用例

ローカル エンドポイント使用してTcpListener クラスインスタンス作成するコード例次に示します

'Creates an instance of the TcpListener class by providing a local endpoint.
Dim ipAddress As IPAddress = Dns.Resolve(Dns.GetHostName()).AddressList(0)
Dim ipLocalEndPoint As New
 IPEndPoint(ipAddress, 11000)

Try
   Dim tcpListener As New
 TcpListener(ipLocalEndPoint)
Catch e As Exception
   Console.WriteLine(e.ToString())
End Try
//Creates an instance of the TcpListener class by providing a local
 endpoint.

IPAddress ipAddress = Dns.Resolve(Dns.GetHostName()).AddressList[0];
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 11000);
 

try{
    TcpListener tcpListener = new TcpListener(ipLocalEndPoint);
}
catch ( Exception e ){
    Console.WriteLine( e.ToString());
}
//Creates an instance of the TcpListener class by providing a local
 endpoint.

IPAddress^ ipAddress = Dns::Resolve( Dns::GetHostName() )->AddressList[ 0 ];
IPEndPoint^ ipLocalEndPoint = gcnew IPEndPoint( ipAddress,11000 );

try
{
   TcpListener^ tcpListener = gcnew TcpListener( ipLocalEndPoint );
}
catch ( Exception^ e ) 
{
   Console::WriteLine( e->ToString() );
}
// Creates an instance of the TcpListener class by providing a 
// local endpoint.
IPAddress ipAddress = (IPAddress)Dns.Resolve(
    Dns.GetHostName()).get_AddressList().get_Item(0);
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 11000);
try {
    TcpListener tcpListener = new TcpListener(ipLocalEndPoint);
}
catch (System.Exception e) {
    Console.WriteLine(e.ToString());
}
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
TcpListener クラス
TcpListener メンバ
System.Net.Sockets 名前空間
IPEndPoint クラス
Start

TcpListener コンストラクタ (IPAddress, Int32)

指定したローカル IP アドレスポート番号受信接続試行待機する、TcpListener クラス新しインスタンス初期化します。

名前空間: System.Net.Sockets
アセンブリ: System (system.dll 内)
構文構文

Public Sub New ( _
    localaddr As IPAddress, _
    port As Integer _
)
Dim localaddr As IPAddress
Dim port As Integer

Dim instance As New TcpListener(localaddr,
 port)
public TcpListener (
    IPAddress localaddr,
    int port
)
public:
TcpListener (
    IPAddress^ localaddr, 
    int port
)
public TcpListener (
    IPAddress localaddr, 
    int port
)
public function TcpListener (
    localaddr : IPAddress, 
    port : int
)

パラメータ

localaddr

ローカル IP アドレスを表す IPAddress

port

受信接続試行待機するポート

例外例外
例外種類条件

ArgumentNullException

localaddrnull 参照 (Visual Basic では Nothing) です。

ArgumentOutOfRangeException

port が MinPort と MaxPort の間の値ではありません。

解説解説

このコンストラクタ使用すると、受信接続試行待機するローカル IP アドレスおよびポート番号指定できます。このコンストラクタ呼び出す前に目的ローカル アドレス使用して IPAddress作成しておく必要があります。このとき、IPAddresslocaladdr パラメータとしてコンストラクタ渡します。どのローカル アドレス割り当ててかまわない場合は、localaddr パラメータに IPAddress.Any を指定します。すると、基になるサービス プロバイダが最も適切なネットワーク アドレス割り当てます複数ネットワーク インターフェイスがある場合は、これを使用することによってアプリケーション簡素化できることあります。どのローカル ポート使用してかまわない場合は、ポート番号を 0 に指定することもできます。この場合サービス プロバイダ10245000範囲使用できるポート番号割り当てますこの方法を使用する場合、LocalEndpoint プロパティ使用することによって、既に割り当てられているローカル ネットワーク アドレスポート番号を知ることができます

Start メソッド呼び出して受信接続試行待機開始します

メモメモ

このメンバは、アプリケーションネットワーク トレース有効にされている場合トレース情報出力します詳細については、「ネットワークトレース」を参照してください

使用例使用例

ローカル IP アドレスポート番号使用してTcpListener クラスインスタンス作成するコード例次に示します

'Creates an instance of the TcpListener class by providing a local IP
 address and port number.
Dim ipAddress As IPAddress = Dns.Resolve("localhost").AddressList(0)

Try
   Dim tcpListener As New
 TcpListener(ipAddress, 13)
Catch e As Exception
   Console.WriteLine(e.ToString())
End Try
         
//Creates an instance of the TcpListener class by providing a local
 IP address and port number.

IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];

try{
    TcpListener tcpListener =  new TcpListener(ipAddress, 13);
    
}
catch ( Exception e){
    Console.WriteLine( e.ToString());
}
    
//Creates an instance of the TcpListener class by providing a local
 IP address and port number.

IPAddress^ ipAddress = Dns::Resolve( "localhost" )->AddressList[ 0 ];

try
{
   TcpListener^ tcpListener = gcnew TcpListener( ipAddress,13 );
}
catch ( Exception^ e ) 
{
   Console::WriteLine( e->ToString() );
}
// Creates an instance of the TcpListener class by providing a 
// local IP address and port number.
IPAddress ipAddress = (IPAddress)Dns.Resolve(
    "localhost").get_AddressList().get_Item(0);
try {
    TcpListener tcpListener = new TcpListener(ipAddress, 13);
}
catch (System.Exception e) {
    Console.WriteLine(e.ToString());
}
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
TcpListener クラス
TcpListener メンバ
System.Net.Sockets 名前空間
IPAddress クラス
Start

TcpListener コンストラクタ


TcpListener プロパティ


TcpListener メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド参照)
  名前 説明
パブリック メソッド AcceptSocket 保留中の接続要求受け入れます
パブリック メソッド AcceptTcpClient 保留中の接続要求受け入れます
パブリック メソッド BeginAcceptSocket 受信接続試行受け入れ非同期操作開始します
パブリック メソッド BeginAcceptTcpClient 受信接続試行受け入れ非同期操作開始します
パブリック メソッド EndAcceptSocket 受信接続試行非同期的に受け入れ新しSocket作成してリモート ホスト通信処理します
パブリック メソッド EndAcceptTcpClient 受信接続試行非同期的に受け入れ新しい TcpClient を作成してリモート ホスト通信処理します
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド Pending 保留中の接続要求があるかどうか確認します
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド Start オーバーロードされます受信接続要求待機開始します
パブリック メソッド Stop リスナ閉じます
パブリック メソッド ToString  現在の Object を表す String返します。 ( Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

TcpListener クラス
System.Net.Sockets 名前空間
TcpClient クラス

TcpListener メンバ

TCP ネットワーク クライアントからの接続待機します。

TcpListener データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
プロテクト プロパティプロテクト プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド参照)
  名前 説明
パブリック メソッド AcceptSocket 保留中の接続要求受け入れます
パブリック メソッド AcceptTcpClient 保留中の接続要求受け入れます
パブリック メソッド BeginAcceptSocket 受信接続試行受け入れ非同期操作開始します
パブリック メソッド BeginAcceptTcpClient 受信接続試行受け入れ非同期操作開始します
パブリック メソッド EndAcceptSocket 受信接続試行非同期的に受け入れ新しSocket作成してリモート ホスト通信処理します
パブリック メソッド EndAcceptTcpClient 受信接続試行非同期的に受け入れ新しい TcpClient を作成してリモート ホスト通信処理します
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド Pending 保留中の接続要求があるかどうか確認します
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド Start オーバーロードされます受信接続要求待機開始します
パブリック メソッド Stop リスナ閉じます
パブリック メソッド ToString  現在の Object を表す String返します。 (Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

TcpListener クラス
System.Net.Sockets 名前空間
TcpClient クラス



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「TcpListener」の関連用語

TcpListenerのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



TcpListenerのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS