Socket クラスとは? わかりやすく解説

Socket クラス

Berkeley ソケット インターフェイス実装ます。

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

解説解説

Socket クラスには、ネットワーク通信のためのメソッドプロパティ豊富に用意されています。Socket クラス使用すると、ProtocolType 列挙体で示されている各種通信プロトコル使い同期または非同期データ転送できますSocket クラスは、.NET Framework での非同期メソッドの名前付け規則に従ってます。たとえば、同期Receive メソッド非同期の BeginReceive メソッドと EndReceive メソッド対応します

実行中に 1 つスレッドしか必要な場合使用するメソッド次に示します。これらのメソッド同期操作モードでの使用想定してます。

実行中に個別スレッド使用して通信処理する場合使用するメソッド次に示します。これらのメソッド非同期操作モードでの使用想定してます。

ソケット上で複数非同期動作実行する場合、各動作実行開始された順に完了するとは限りません。

データの送受信完了したら、Shutdown メソッド使用して Socket無効にます。Shutdown呼び出してから Close メソッド呼び出してSocket関連付けられているすべてのリソース解放します。

Socket クラス使用すると、SetSocketOption メソッド使用して Socket設定できます。これらの設定取得するには、GetSocketOption メソッド使用します

メモメモ

比較単純なアプリケーション記述しており、最高のパフォーマンスを必要としない場合は、TcpClient、TcpListener、および UdpClient を使用することを検討してください。これらのクラスには、Socket 通信を行うためのより単純でわかりやすいインターフェイス用意されています。

Windows Mobile for Pocket PCWindows Mobile for SmartphoneWindows 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
.NET Framework のセキュリティ.NET Frameworkセキュリティ
継承階層継承階層
System.Object
  System.Net.Sockets.Socket
スレッド セーフスレッド セーフ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



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

辞書ショートカット

すべての辞書の索引

「Socket クラス」の関連用語

Socket クラスのお隣キーワード
検索ランキング

   

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



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

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

©2024 GRAS Group, Inc.RSS