TcpListener クラス
アセンブリ: System (system.dll 内)


TcpListener クラスは、同期ブロッキング モードのときに受信接続要求を待機したり受け取ったりする単純なメソッドを提供します。TcpListener に接続するには、TcpClient または Socket のいずれかを使用できます。IPEndPoint、ローカル IP アドレスとポート番号、またはポート番号だけを使用して、TcpListener を作成します。基になるサービス プロバイダがこれらの値を割り当てるようにするには、ローカル IP アドレスには Any を、ローカル ポート番号には 0 を指定します。このように指定した場合は、LocalEndpoint プロパティを使用すると、ソケットが接続された後で、割り当てられた情報を確認できます。
Start メソッドを使用して、受信接続要求の待機を開始します。Start は、Stop メソッドが呼び出されるか、MaxConnections がキューに置かれるまでは、受信接続要求をキューに置きます。AcceptSocket または AcceptTcpClient のいずれかを使用して、受信接続要求のキューから接続を引き出します。この 2 つのメソッドはブロックします。ブロックしないようにする場合は、まず、Pending メソッドを使用して、接続要求がキュー内で使用可能かどうかを確認します。
TcpListener を閉じるには、Stop メソッドを使用します。
![]() |
---|

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(); }


System.Net.Sockets.TcpListener


Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


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 )


このコンストラクタは今後は使用しません。System.Net.Sockets.TcpListener(IPAddress,Int32) コンストラクタまたは System.Net.Sockets.TcpListener(IPEndPoint) コンストラクタを使用します。
このコンストラクタを使用すると、受信接続の試行を待機するポート番号を指定できます。基になるサービス プロバイダは、このコンストラクタを使用して最も適切なネットワーク アドレスを割り当てます。どのローカル ポートを使用してもかまわない場合は、ポート番号を 0 に指定することもできます。この場合、サービス プロバイダは 1024 ~ 5000 の範囲で使用できるポート番号を割り当てます。この方法を使用する場合、LocalEndpoint プロパティを使用することによって、既に割り当てられているローカル ネットワーク アドレスとポート番号を知ることができます。

ローカル ポート番号を使用して、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()); }

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。

サポート対象 : 1.0、1.1
2.0 では、互換性のために残されています (コンパイル時に警告)
.NET Compact Framework
サポート対象 : 1.0
2.0 では、互換性のために残されています (コンパイル時に警告)

TcpListener コンストラクタ (IPEndPoint)
アセンブリ: System (system.dll 内)



このコンストラクタを使用すると、受信接続の試行を待機するローカル IP アドレスおよびポート番号を指定できます。このコンストラクタを使用する前に、目的のローカル IP アドレスおよびポート番号を使用して IPEndPoint を作成しておく必要があります。このとき、IPEndPoint を localEP パラメータとしてコンストラクタに渡します。
どのローカル アドレスが割り当てられていてもかまわない場合は、IPAddress.Any をアドレス パラメータとして使用して IPEndPoint を作成します。すると、基になるサービス プロバイダが最も適切なローカル ネットワーク アドレスを割り当てます。複数のネットワーク インターフェイスがある場合は、これを使用することによってアプリケーションを簡素化できることがあります。使用するローカル ポートについても特に指定がない場合は、ポート番号 0 を使用して IPEndPoint を作成します。この場合、サービス プロバイダは 1024 ~ 5000 の範囲で使用できるポート番号を割り当てます。この方法を使用する場合、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()); }

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


TcpListener コンストラクタ (IPAddress, Int32)
アセンブリ: System (system.dll 内)

- localaddr


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

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


TcpListener コンストラクタ

名前 | 説明 |
---|---|
TcpListener (Int32) | 指定したポートを待機する TcpListener クラスの新しいインスタンスを初期化します。 .NET Compact Framework によってサポートされています。 |
TcpListener (IPEndPoint) | 指定したローカル エンドポイントを使用して、TcpListener クラスの新しいインスタンスを初期化します。 .NET Compact Framework によってサポートされています。 |
TcpListener (IPAddress, Int32) | 指定したローカル IP アドレスとポート番号で受信接続の試行を待機する、TcpListener クラスの新しいインスタンスを初期化します。 .NET Compact Framework によってサポートされています。 |

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 から継承されます。) |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 ( Object から継承されます。) |

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 から継承されます。) |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 (Object から継承されます。) |

- TcpListenerのページへのリンク