Socket クラス
アセンブリ: System (system.dll 内)
構文
Public Class Socket Implements IDisposable
public class Socket implements IDisposable
public class Socket implements IDisposable
Socket クラスには、ネットワーク通信のためのメソッドとプロパティが豊富に用意されています。Socket クラスを使用すると、ProtocolType 列挙体で示されている各種の通信プロトコルを使い、同期または非同期でデータを転送できます。Socket クラスは、.NET Framework での非同期メソッドの名前付け規則に従っています。たとえば、同期の Receive メソッドは非同期の BeginReceive メソッドと EndReceive メソッドに対応します。
実行中に 1 つのスレッドしか必要ない場合に使用するメソッドを次に示します。これらのメソッドは同期操作モードでの使用を想定しています。
-
TCP などのコネクション指向のプロトコルを使用する場合、サーバーは Listen メソッドを使用して接続を待機します。Accept メソッドは受信接続要求を処理して、リモート ホストとのデータ通信に使用できる Socket を返します。この返された Socket を使用して、Send メソッドまたは Receive メソッドを呼び出します。ローカル IP アドレスとポート番号を指定する場合は、Listen メソッドの前に Bind メソッドを呼び出します。基になるサービス プロバイダによって空きポートが割り当てられるようにする場合は、ポート番号に 0 を使用します。待機中のホストに接続する必要がある場合は、Connect メソッドを呼び出します。データを送受信するには、Send メソッドまたは Receive メソッドを呼び出します。
-
UDP などのコネクションレスのプロトコルを使用している場合は、接続を待機する必要はありません。ReceiveFrom メソッドを呼び出して、受信データグラムを受け取ります。データグラムをリモート ホストに送信するには、SendTo メソッドを使用します。
実行中に個別のスレッドを使用して通信を処理する場合に使用するメソッドを次に示します。これらのメソッドは非同期操作モードでの使用を想定しています。
-
TCP などのコネクション指向のプロトコルを使用する場合は、Socket メソッド、BeginConnect メソッド、および EndConnect メソッドを使用して待機中のホストと通信します。データの非同期的な送受信には、BeginSend メソッドと EndSend メソッドまたは BeginReceive メソッドと EndReceive メソッドを使用します。BeginAccept および EndAccept を使用すると、受信接続要求を処理できます。
-
UDP などのコネクションレスのプロトコルを使用している場合は、BeginSendTo および EndSendTo を使用してデータグラムを送信します。データグラムの受信には、BeginReceiveFrom と EndReceiveFrom を使用します。
ソケット上で複数の非同期動作を実行する場合、各動作の実行は開始された順に完了するとは限りません。
データの送受信が完了したら、Shutdown メソッドを使用して Socket を無効にします。Shutdown を呼び出してから Close メソッドを呼び出して、Socket に関連付けられているすべてのリソースを解放します。
Socket クラスを使用すると、SetSocketOption メソッドを使用して Socket を設定できます。これらの設定を取得するには、GetSocketOption メソッドを使用します。
メモ |
---|
比較的単純なアプリケーションを記述しており、最高のパフォーマンスを必要としない場合は、TcpClient、TcpListener、および UdpClient を使用することを検討してください。これらのクラスには、Socket 通信を行うためのより単純でわかりやすいインターフェイスが用意されています。 |
Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows CE プラットフォームメモ : すべてのデバイスのオペレーティング システムで、すべてのソケット オプションがサポートされているわけではありません。
Socket クラスを使用して、データを HTTP サーバーに送信し、応答を受信する方法を次のコード例に示します。この例は、すべてのページを受信するまでブロックします。
Imports System Imports System.Text Imports System.IO Imports System.Net Imports System.Net.Sockets Imports Microsoft.VisualBasic Public Class GetSocket Private Shared Function ConnectSocket(server As String, port As Integer) As Socket Dim s As Socket = Nothing Dim hostEntry As IPHostEntry = Nothing ' Get host related information. hostEntry = Dns.GetHostEntry(server) ' Loop through the AddressList to obtain the supported AddressFamily. This is to avoid ' an exception that occurs when the host host IP Address is not compatible with the address family ' (typical in the IPv6 case). Dim address As IPAddress For Each address In hostEntry.AddressList Dim endPoint As New IPEndPoint(address, port) Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) tempSocket.Connect(endPoint) If tempSocket.Connected Then s = tempSocket Exit For End If Next address Return s End Function ' This method requests the home page content for the specified server. Private Shared Function SocketSendReceive(server As String, port As Integer) As String 'Set up variables and String to write to the server. Dim ascii As Encoding = Encoding.ASCII Dim request As String = "GET / HTTP/1.1" + ControlChars.Cr + ControlChars.Lf + "Host: " + server + ControlChars.Cr + ControlChars.Lf + "Connection: Close" + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf Dim bytesSent As [Byte]() = ascii.GetBytes(request) Dim bytesReceived(255) As [Byte] ' Create a socket connection with the specified server and port. Dim s As Socket = ConnectSocket(server, port) If s Is Nothing Then Return "Connection failed" End If ' Send request to the server. s.Send(bytesSent, bytesSent.Length, 0) ' Receive the server home page content. Dim bytes As Int32 ' Read the first 256 bytes. Dim page as [String] = "Default HTML page on " + server + ":" + ControlChars.Cr + ControlChars.Lf ' The following will block until the page is transmitted. Do bytes = s.Receive(bytesReceived, bytesReceived.Length, 0) page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes) Loop While bytes > 0 Return page End Function 'Entry point which delegates to C-style main Private Function Public Overloads Shared Sub Main() Main(System.Environment.GetCommandLineArgs()) End Sub Overloads Private Shared Sub Main(args() As String) Dim host As String Dim port As Integer = 80 If args.Length = 1 Then ' If no server name is passed as argument to this program, ' use the current host name as default. host = Dns.GetHostName() Else host = args(1) End If Dim result As String = SocketSendReceive(host, port) Console.WriteLine(result) End Sub 'Main End Class
using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; public class GetSocket { private static Socket ConnectSocket(string server, int port) { Socket s = null; IPHostEntry hostEntry = null; // Get host related information. hostEntry = Dns.GetHostEntry(server); // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). foreach(IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if(tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return s; } // This method requests the home page content for the specified server. private static string SocketSendReceive(string server, int port) { string request = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; Byte[] bytesSent = Encoding.ASCII.GetBytes(request); Byte[] bytesReceived = new Byte[256]; // Create a socket connection with the specified server and port. Socket s = ConnectSocket(server, port); if (s == null) return ("Connection failed"); // Send request to the server. s.Send(bytesSent, bytesSent.Length, 0); // Receive the server home page content. int bytes = 0; string page = "Default HTML page on " + server + ":\r\n"; // The following will block until te page is transmitted. do { bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes); } while (bytes > 0); return page; } public static void Main(string[] args) { string host; int port = 80; if (args.Length == 0) // If no server name is passed as argument to this program, // use the current host name as the default. host = Dns.GetHostName(); else host = args[0]; string result = SocketSendReceive(host, port); Console.WriteLine(result); } }
#using <System.dll> using namespace System; using namespace System::Text; using namespace System::IO; using namespace System::Net; using namespace System::Net::Sockets; using namespace System::Collections; Socket^ ConnectSocket( String^ server, int port ) { Socket^ s = nullptr; IPHostEntry^ hostEntry = nullptr; // Get host related information. hostEntry = Dns::Resolve( server ); // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). IEnumerator^ myEnum = hostEntry->AddressList->GetEnumerator(); while ( myEnum->MoveNext() ) { IPAddress^ address = safe_cast<IPAddress^>(myEnum->Current); IPEndPoint^ endPoint = gcnew IPEndPoint( address,port ); Socket^ tmpS = gcnew Socket( endPoint->AddressFamily,SocketType::Stream,ProtocolType::Tcp ); tmpS->Connect( endPoint ); if ( tmpS->Connected ) { s = tmpS; break; } else { continue; } } return s; } // This method requests the home page content for the specified server. String^ SocketSendReceive( String^ server, int port ) { String^ request = String::Concat( "GET / HTTP/1.1\r\nHost: ", server, "\r\nConnection: Close\r\n\r\n" ); array<Byte>^bytesSent = Encoding::ASCII->GetBytes( request ); array<Byte>^bytesReceived = gcnew array<Byte>(256); // Create a socket connection with the specified server and port. Socket^ s = ConnectSocket( server, port ); if ( s == nullptr ) return ("Connection failed"); // Send request to the server. s->Send( bytesSent, bytesSent->Length, static_cast<SocketFlags>(0) ); // Receive the server home page content. int bytes = 0; String^ strRetPage = String::Concat( "Default HTML page on ", server, ":\r\n" ); do { bytes = s->Receive( bytesReceived, bytesReceived->Length, static_cast<SocketFlags>(0) ); strRetPage = String::Concat( strRetPage, Encoding::ASCII->GetString( bytesReceived, 0, bytes ) ); } while ( bytes > 0 ); return strRetPage; } int main() { array<String^>^args = Environment::GetCommandLineArgs(); String^ host; int port = 80; if ( args->Length == 1 ) // If no server name is passed as argument to this program, // use the current host name as default. host = Dns::GetHostName(); else host = args[ 1 ]; String^ result = SocketSendReceive( host, port ); Console::WriteLine( result ); }
import System.*; import System.Text.*; import System.IO.*; import System.Net.*; import System.Net.Sockets.*; public class GetSocket { private static Socket ConnectSocket(String server, int port) { Socket s = null; IPHostEntry hostEntry = null; // Get host related information. hostEntry = Dns.Resolve(server); // Loop through the AddressList to obtain the supported AddressFamily. // This is to avoid an exception that occurs when the host IP Address // is not compatible with the address family // (typical in the IPv6 case). for (int iCtr = 0; iCtr < hostEntry.get_AddressList().length; iCtr++) { IPAddress address = hostEntry.get_AddressList()[iCtr]; IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.get_AddressFamily() , SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if (tempSocket.get_Connected()) { s = tempSocket; break; } else { continue; } } return s; } //ConnectSocket // This method requests the home page content for the specified server. private static String SocketSendReceive(String server, int port) { String request = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; System.Byte bytesSent[] = (System.Byte[])Encoding.get_ASCII().GetBytes(request); System.Byte bytesReceived[] = new System.Byte[256]; // Create a socket connection with the specified server and port. Socket s = ConnectSocket(server, port); if (s == null) { return "Connection failed"; } // Send request to the server. s.Send((ubyte[])bytesSent, bytesSent.length, (SocketFlags)0); // Receive the server home page content. int bytes = 0; String page = "Default HTML page on " + server + ":\r\n"; // The following will block until te page is transmitted. do { bytes = s.Receive((ubyte[])bytesReceived, bytesReceived.length, (SocketFlags)0); page = page + Encoding.get_ASCII().GetString( (ubyte[])bytesReceived, 0, bytes); } while (bytes > 0); return page; } //SocketSendReceive public static void main(String[] args) { String host; int port = 80; if (args.length == 0) { // If no server name is passed as argument to this program, // use the current host name as the default. host = Dns.GetHostName(); } else { host = args[0]; } String result = SocketSendReceive(host, port); Console.WriteLine(result); } //main } //GetSocket
継承階層
System.Net.Sockets.Socket
プラットフォーム
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 によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
Weblioに収録されているすべての辞書からSocket クラスを検索する場合は、下記のリンクをクリックしてください。
全ての辞書からSocket クラスを検索
- Socket クラスのページへのリンク