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

socket

別表記:ソケット

「socket」とは・「socket」の意味

「socket」は、日本語で「ソケット」あるいは「差込口」と訳されることが多い。電気製品におけるプラグを差し込む部分や、コンピューターのネットワーク通信におけるエンドポイントを指すことが多い。また、工具においては、ボルトやナットを回すための工具の一部を指すこともある。

「socket」の発音・読み方

「socket」の発音は、IPA表記では /ˈsɒkɪt/ となる。IPAのカタカナ読みでは「サキット」となる。日本人が発音するカタカナ英語では「ソケット」と読む。発音によって意味や品詞が変わる単語ではない。

「socket」の定義を英語で解説

A socket is a device or point in a system where an electrical device can be plugged in or a tool can be inserted. In the context of computer networking, a socket is an endpoint in a communication.

「socket」の類語

「socket」の類語としては、「outlet」や「receptacle」がある。これらも電気製品のプラグを差し込む部分を指す言葉である。ただし、「outlet」は主にアメリカ英語で、「receptacle」は少し古風な表現である。

「socket」に関連する用語・表現

「socket」に関連する用語としては、「plug」がある。これは「socket」に差し込む部分を指す。また、コンピューターのネットワーク通信における「socket」に関連しては、「IP address」や「port number」がある。これらは「socket」を特定するための情報である。

「socket」の例文

以下に「socket」を用いた例文を10個示す。 1. English: The lamp is plugged into the socket.
日本語訳: ランプはソケットに差し込まれている。 2. English: The socket wrench is used to tighten the bolts.
日本語訳: ソケットレンチはボルトを締めるために使われる。 3. English: The socket is designed for a two-pin plug.
日本語訳: そのソケットは2ピンのプラグ用に設計されている。 4. English: The server creates a socket and listens for incoming connections.
日本語訳: サーバーはソケットを作成し、着信接続を待ち受ける。 5. English: The socket is located behind the desk.
日本語訳: ソケットはデスクの後ろに位置している。 6. English: The socket is not working properly.
日本語訳: ソケットが正常に動作していない。 7. English: The socket provides a connection to the electrical grid.
日本語訳: ソケットは電力網への接続を提供する。 8. English: The socket is used to connect the device to the power supply.
日本語訳: ソケットはデバイスを電源に接続するために使用される。 9. English: The socket accepts a three-pronged plug.
日本語訳: そのソケットは3本ピンのプラグを受け入れる。 10. English: The socket is part of the computer's hardware.
日本語訳: ソケットはコンピュータのハードウェアの一部である。

ソケット【socket】

読み方:そけっと

1 器具などをはめ込むためのくぼみ。受け口。

2 電球や蛍光灯などを差し込むときの受け口となる、コードの先端部の器具。

3 コンピューターのCPUやメモリーを基板などに取り付けるための受け口。


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 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
.NET Framework のセキュリティ.NET Framework のセキュリティ
継承階層継承階層
System.Object
  System.Net.Sockets.Socket
スレッド セーフスレッド セーフ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
Socket メンバ
System.Net.Sockets 名前空間

Socket コンストラクタ (AddressFamily, SocketType, ProtocolType)

指定したアドレス ファミリ、ソケット タイプ、およびプロトコルを使用して、Socket クラスの新しいインスタンスを初期化します。

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

Public Sub New ( _
    addressFamily As AddressFamily, _
    socketType As SocketType, _
    protocolType As ProtocolType _
)
Dim addressFamily As AddressFamily
Dim socketType As SocketType
Dim protocolType As ProtocolType

Dim instance As New Socket(addressFamily,
 socketType, protocolType)
public Socket (
    AddressFamily addressFamily,
    SocketType socketType,
    ProtocolType protocolType
)
public:
Socket (
    AddressFamily addressFamily, 
    SocketType socketType, 
    ProtocolType protocolType
)
public Socket (
    AddressFamily addressFamily, 
    SocketType socketType, 
    ProtocolType protocolType
)
public function Socket (
    addressFamily : AddressFamily, 
    socketType : SocketType, 
    protocolType : ProtocolType
)

パラメータ

addressFamily

AddressFamily 値の 1 つ。

socketType

SocketType 値の 1 つ。

protocolType

ProtocolType 値の 1 つ。

例外例外
例外の種類条件

SocketException

addressFamily、socketType、および protocolType を組み合わせると、無効なソケットになります。

解説解説
使用例使用例

Socket クラスのインスタンスを作成する方法を次のコード例に示します。

Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Net.Sockets

 _

Public Class Sample
   
   
   Public Shared Function
 DoSocketGet(server As String) As
 String
      'Set up variables and String to write to the server.
    Dim ASCII As Encoding = Encoding.ASCII
    Dim [Get] As String
 = "GET / HTTP/1.1" + ControlChars.Lf + ControlChars.NewLine
 + "Host: " + server + ControlChars.Lf + ControlChars.NewLine + "Connection: Close" + ControlChars.Lf
 + ControlChars.NewLine + ControlChars.Lf + ControlChars.NewLine
    Dim ByteGet As [Byte]() = ASCII.GetBytes([Get])
    Dim RecvBytes(256) As [Byte]
    Dim strRetPage As [String] = Nothing


      
      ' IPAddress and IPEndPoint represent the endpoint that will
      '   receive the request.
      ' Get first IPAddress in list return by DNS.
      Try

 

         ' Define those variables to be evaluated in the next for loop
 and 
         ' then used to connect to the server. These variables are defined
         ' outside the for loop to make them accessible there after.
         Dim s As Socket = Nothing
         Dim hostEndPoint As IPEndPoint
         Dim hostAddress As IPAddress = Nothing
         Dim conPort As Integer
 = 80
         
         ' Get DNS host information.
         Dim hostInfo As IPHostEntry = Dns.Resolve(server)
         ' Get the DNS IP addresses associated with the host.
         Dim IPaddresses As IPAddress() = hostInfo.AddressList
         
         ' Evaluate the socket and receiving host IPAddress and IPEndPoint.
 
      Dim index As Integer
 = 0
      For index = 0 To IPaddresses.Length -
 1
        hostAddress = IPaddresses(index)
        hostEndPoint = New IPEndPoint(hostAddress, conPort)


        ' Creates the Socket to send data over a TCP connection.
        s = New Socket(AddressFamily.InterNetwork, SocketType.Stream,
 ProtocolType.Tcp)


        ' Connect to the host using its IPEndPoint.
        s.Connect(hostEndPoint)

        If Not s.Connected Then
          ' Connection failed, try next IPaddress.
          strRetPage = "Unable to connect to host"
          s = Nothing
          GoTo ContinueFor1
        End If


        ' Sent the GET request to the host.
        s.Send(ByteGet, ByteGet.Length, 0)


ContinueFor1:
      Next index  ' End of the for loop.
      



      ' Receive the host home page content and loop until all the data
 is received.

      'Dim bytes As Int32 = s.Receive(RecvBytes, RecvBytes.Length, 0)
      Dim bytes As Int32 = s.Receive(RecvBytes,
 RecvBytes.Length, 0)

      strRetPage = "Default HTML page on " + server
 + ":\r\n"
      strRetPage = "Default HTML page on " + server
 + ":" + ControlChars.Lf + ControlChars.NewLine

      Dim i As Integer

      While bytes > 0

        bytes = s.Receive(RecvBytes, RecvBytes.Length, 0)

        strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes)

      End While


      ' End of the try block.
    Catch e As SocketException
         Console.WriteLine("SocketException caught!!!")
         Console.WriteLine(("Source : " + e.Source))
         Console.WriteLine(("Message : " + e.Message))
      Catch e As ArgumentNullException
         Console.WriteLine("ArgumentNullException caught!!!")
         Console.WriteLine(("Source : " + e.Source))
         Console.WriteLine(("Message : " + e.Message))
      Catch e As NullReferenceException
         Console.WriteLine("NullReferenceException caught!!!")
         Console.WriteLine(("Source : " + e.Source))
         Console.WriteLine(("Message : " + e.Message))
      Catch e As Exception
         Console.WriteLine("Exception caught!!!")
         Console.WriteLine(("Source : " + e.Source))
         Console.WriteLine(("Message : " + e.Message))
      End Try
      
      Return strRetPage
   End Function 'DoSocketGet
    
   Public Shared Sub Main()
    Console.WriteLine(DoSocketGet("localhost"))
   End Sub 'Main
End Class 'Sample
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

public class Sample
{

  public static string DoSocketGet(string
 server) 
  {
    //Set up variables and String to write to the server.
    Encoding ASCII = Encoding.ASCII;
    string Get = "GET / HTTP/1.1\r\nHost: " + server
 + 
                 "\r\nConnection: Close\r\n\r\n";
    Byte[] ByteGet = ASCII.GetBytes(Get);
    Byte[] RecvBytes = new Byte[256];
    String strRetPage = null;


    // IPAddress and IPEndPoint represent the endpoint that will
    //   receive the request.
    // Get first IPAddress in list return by DNS.


    try
    {


      // Define those variables to be evaluated in the next for loop
 and 
      // then used to connect to the server. These variables are defined
      // outside the for loop to make them accessible there after.
      Socket s = null;
      IPEndPoint hostEndPoint;
      IPAddress hostAddress = null;
      int conPort = 80;

      // Get DNS host information.
      IPHostEntry hostInfo = Dns.GetHostEntry(server);
      // Get the DNS IP addresses associated with the host.
      IPAddress[] IPaddresses = hostInfo.AddressList;

      // Evaluate the socket and receiving host IPAddress and IPEndPoint.
 
      for (int index=0; index<IPaddresses.Length;
 index++)
      {
        hostAddress = IPaddresses[index];
        hostEndPoint = new IPEndPoint(hostAddress, conPort);


        // Creates the Socket to send data over a TCP connection.
        s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
 ProtocolType.Tcp );


 
        // Connect to the host using its IPEndPoint.
        s.Connect(hostEndPoint);

        if (!s.Connected)
        {
          // Connection failed, try next IPaddress.
          strRetPage = "Unable to connect to host";
          s = null;
          continue;
        }

        // Sent the GET request to the host.
        s.Send(ByteGet, ByteGet.Length, 0);


      } // End of the for loop.      


 
      // Receive the host home page content and loop until all the data
 is received.
      Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
      strRetPage = "Default HTML page on " + server + ":\r\n";
      strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
 
      while (bytes > 0)
      {
        bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
        strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
      }

    
    } // End of the try block.
    
    catch(SocketException e) 
    {
      Console.WriteLine("SocketException caught!!!");
      Console.WriteLine("Source : " + e.Source);
      Console.WriteLine("Message : " + e.Message);
    }
    catch(ArgumentNullException e)
    {
      Console.WriteLine("ArgumentNullException caught!!!");
      Console.WriteLine("Source : " + e.Source);
      Console.WriteLine("Message : " + e.Message);
    }
    catch(NullReferenceException e)
    {
      Console.WriteLine("NullReferenceException caught!!!");
      Console.WriteLine("Source : " + e.Source);
      Console.WriteLine("Message : " + e.Message);
    }
    catch(Exception e)
    {
      Console.WriteLine("Exception caught!!!");
      Console.WriteLine("Source : " + e.Source);
      Console.WriteLine("Message : " + e.Message);
    }
    
    return strRetPage;

}
   public static void Main()
   {
      Console.WriteLine(DoSocketGet("localhost"));
   }
 }
#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
String^ DoSocketGet( String^ server )
{
   
   //Set up variables and String to write to the server.
   Encoding^ ASCII = Encoding::ASCII;
   String^ Get =  "GET / HTTP/1.1\r\nHost: ";
   Get->Concat( server,  "\r\nConnection: Close\r\n\r\n" );
   array<Byte>^ByteGet = ASCII->GetBytes( Get );
   array<Byte>^RecvBytes = gcnew array<Byte>(256);
   String^ strRetPage = nullptr;
   
   // IPAddress and IPEndPoint represent the endpoint that will
   //   receive the request.
   // Get first IPAddress in list return by DNS.
   try
   {
      
      // Define those variables to be evaluated in the next for loop
 and 
      // then used to connect to the server. These variables are defined
      // outside the for loop to make them accessible there after.
      Socket^ s = nullptr;
      IPEndPoint^ hostEndPoint;
      IPAddress^ hostAddress = nullptr;
      int conPort = 80;
      
      // Get DNS host information.
      IPHostEntry^ hostInfo = Dns::Resolve( server );
      
      // Get the DNS IP addresses associated with the host.
      array<IPAddress^>^IPaddresses = hostInfo->AddressList;
      
      // Evaluate the socket and receiving host IPAddress and IPEndPoint.
 
      for ( int index = 0; index < IPaddresses->Length;
 index++ )
      {
         hostAddress = IPaddresses[ index ];
         hostEndPoint = gcnew IPEndPoint( hostAddress,conPort );
         
         // Creates the Socket to send data over a TCP connection.
         s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp
 );
         
         // Connect to the host using its IPEndPoint.
         s->Connect( hostEndPoint );
         if (  !s->Connected )
         {
            
            // Connection failed, try next IPaddress.
            strRetPage =  "Unable to connect to host";
            s = nullptr;
            continue;
         }

         
         // Sent the GET request to the host.
         s->Send( ByteGet, ByteGet->Length, SocketFlags::None );
         

      }
      
      // Receive the host home page content and loop until all the data
 is received.
      Int32 bytes = s->Receive( RecvBytes, RecvBytes->Length, SocketFlags::None
 );
      strRetPage =  "Default HTML page on ";
      strRetPage->Concat( server,  ":\r\n", ASCII->GetString( RecvBytes,
 0, bytes ) );
      while ( bytes > 0 )
      {
         bytes = s->Receive( RecvBytes, RecvBytes->Length, SocketFlags::None
 );
         strRetPage->Concat( ASCII->GetString( RecvBytes, 0, bytes ) );
      }

      
   }
   catch ( SocketException^ e ) 
   {
      Console::WriteLine(  "SocketException caught!!!" );
      Console::Write(  "Source : " );
      Console::WriteLine( e->Source );
      Console::Write(  "Message : " );
      Console::WriteLine( e->Message );
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine(  "ArgumentNULLException caught!!!" );
      Console::Write(  "Source : " );
      Console::WriteLine( e->Source );
      Console::Write(  "Message : " );
      Console::WriteLine( e->Message );
   }
   catch ( NullReferenceException^ e ) 
   {
      Console::WriteLine(  "NULLReferenceException caught!!!" );
      Console::Write(  "Source : " );
      Console::WriteLine( e->Source );
      Console::Write(  "Message : " );
      Console::WriteLine( e->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine(  "Exception caught!!!" );
      Console::Write(  "Source : " );
      Console::WriteLine( e->Source );
      Console::Write(  "Message : " );
      Console::WriteLine( e->Message );
   }

   return strRetPage;
}

int main()
{
   Console::WriteLine( DoSocketGet(  "localhost" ) );
}

import System.*;
import System.Text.*;
import System.IO.*;
import System.Net.*;
import System.Net.Sockets.*;

public class Sample
{
    public static String DoSocketGet(String
 server)
    {
        //Set up variables and String to write to the server.
        Encoding ascii = Encoding.get_ASCII();
        String get = "GET / HTTP/1.1\r\nHost: " + server
            + "\r\nConnection: Close\r\n\r\n";
        System.Byte byteGet[] = (System.Byte[])ascii.GetBytes(get);
        System.Byte recvBytes[] = new System.Byte[256];
        String strRetPage = null;
        // IPAddress and IPEndPoint represent the endpoint that will
        // receive the request.
        // Get first IPAddress in list return by DNS.
        try {
            // Define those variables to be evaluated in the next for
 loop and
            // then used to connect to the server. These variables are
 defined
            // outside the for loop to make them accessible there after.
            Socket s = null;
            IPEndPoint hostEndPoint;
            IPAddress hostAddress = null;
            int conPort = 80;
            // Get DNS host information.
            IPHostEntry hostInfo = Dns.Resolve(server);
            // Get the DNS IP addresses associated with the host.
            IPAddress IPaddresses[] = hostInfo.get_AddressList();
            // Evaluate the socket and receiving host IPAddress and
 IPEndPoint.
            for (int index = 0; index <
 IPaddresses.length; index++) {
                hostAddress = IPaddresses[index];
                hostEndPoint = new IPEndPoint(hostAddress, conPort);
                // Creates the Socket to send data over a TCP connection.
                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream
,
                    ProtocolType.Tcp);
                // Connect to the host using its IPEndPoint.
                s.Connect(hostEndPoint);
                if (!(s.get_Connected())) {
                    // Connection failed, try next IPaddress.
                    strRetPage = "Unable to connect to host";
                    s = null;
                    continue;
                }
                // Sent the GET request to the host.
                s.Send((ubyte[])byteGet, byteGet.get_Length(), (SocketFlags)0);
            } // End of the for loop.      
            // Receive the host home page content and loop until all
 the 
            // data is received.
            Int32 bytes = (Int32)s.Receive((ubyte[])recvBytes,
                recvBytes.get_Length(), (SocketFlags)0);
            strRetPage = "Default HTML page on " + server + ":\r\n";
            strRetPage = strRetPage + ascii.GetString((ubyte[])recvBytes,
                0, Convert.ToInt32(bytes));

            while (Convert.ToInt32(bytes) > 0) {
                bytes = (Int32)s.Receive((ubyte[])recvBytes,
                    recvBytes.get_Length(), (SocketFlags)0);
                strRetPage = strRetPage
                    + ascii.GetString((ubyte[])recvBytes, 0,
                    Convert.ToInt32(bytes));
            }
        } // End of the try block.
        catch (SocketException e) {
            Console.WriteLine("SocketException caught!!!");
            Console.WriteLine("Source : " + e.get_Source());
            Console.WriteLine("Message : " + e.get_Message());
        }
        catch (ArgumentNullException e) {
            Console.WriteLine("ArgumentNullException caught!!!");
            Console.WriteLine("Source : " + e.get_Source());
            Console.WriteLine("Message : " + e.get_Message());
        }
        catch (NullReferenceException e) {
            Console.WriteLine("NullReferenceException caught!!!");
            Console.WriteLine("Source : " + e.get_Source());
            Console.WriteLine("Message : " + e.get_Message());
        }
        catch (System.Exception e) {
            Console.WriteLine("Exception caught!!!");
            Console.WriteLine("Source : " + e.get_Source());
            Console.WriteLine("Message : " + e.get_Message());
        }
        return strRetPage;
    } //DoSocketGet

    public static void main(String[]
 args)
    {
        Console.WriteLine(DoSocketGet("localhost"));
    } //main
} //Sample
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
Socket クラス
Socket メンバ
System.Net.Sockets 名前空間
SocketException
AddressFamily 列挙体
ProtocolType 列挙体
SocketType

Socket コンストラクタ (SocketInformation)

メモ : このコンストラクタは、.NET Framework version 2.0 で新しく追加されたものです。

DuplicateAndClose から返された値を指定して、Socket クラスの新しいインスタンスを初期化します。

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

Public Sub New ( _
    socketInformation As SocketInformation _
)
Dim socketInformation As SocketInformation

Dim instance As New Socket(socketInformation)
public Socket (
    SocketInformation socketInformation
)
public:
Socket (
    SocketInformation socketInformation
)
public Socket (
    SocketInformation socketInformation
)
public function Socket (
    socketInformation : SocketInformation
)

パラメータ

socketInformation

DuplicateAndClose によって返されるソケット情報。

解説解説

Socket コンストラクタを複数回呼び出し、毎回同じバイト配列を引数として渡すと、基になるソケットが同じである複数のマネージ Socket が作成されます。このような処理は、できる限り避けてください。

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

Socket コンストラクタ

Socket クラスの新しいインスタンスを初期化します。
オーバーロードの一覧オーバーロードの一覧

名前 説明
Socket (SocketInformation) DuplicateAndClose から返された値を指定して、Socket クラスの新しいインスタンスを初期化します。
Socket (AddressFamily, SocketType, ProtocolType) 指定したアドレス ファミリ、ソケット タイプ、およびプロトコルを使用して、Socket クラスの新しいインスタンスを初期化します。

.NET Compact Framework によってサポートされています。

参照参照

関連項目

Socket クラス
Socket メンバ
System.Net.Sockets 名前空間

Socket プロパティ


Socket メソッド


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

( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド Accept 新しく作成された接続に対して新しい Socket を作成します。
パブリック メソッド BeginAccept オーバーロードされます。 受信接続の試行を受け入れる非同期操作を開始します。
パブリック メソッド BeginConnect オーバーロードされます。 リモート ホスト接続への非同期要求を開始します。
パブリック メソッド BeginDisconnect リモート エンドポイントからの接続解除の非同期要求を開始します。
パブリック メソッド BeginReceive オーバーロードされます。 接続されている Socket からの非同期のデータ受信を開始します。
パブリック メソッド BeginReceiveFrom 指定したネットワーク デバイスから、データの非同期の受信を開始します。
パブリック メソッド BeginReceiveMessageFrom 指定した SocketFlags を使用し、指定したバイト数のデータの非同期受信を開始して、データ バッファ内の指定した位置に格納します。さらに、エンドポイントとパケット情報を格納します。
パブリック メソッド BeginSend オーバーロードされます。 接続されている Socket にデータを非同期的に送信します。
パブリック メソッド BeginSendFile オーバーロードされます。 接続された Socket オブジェクトに、ファイルを非同期的に送信します。
パブリック メソッド BeginSendTo 特定のリモート ホストにデータを非同期的に送信します。
パブリック メソッド Bind Socket をローカル エンドポイントと関連付けます。
パブリック メソッド Close オーバーロードされます。 Socket 接続を閉じ、関連付けられたすべてのリソースを解放します。
パブリック メソッド Connect オーバーロードされます。 リモート ホストへの接続を確立します。
パブリック メソッド Disconnect ソケット接続を閉じ、ソケットを再利用できるようにします。
パブリック メソッド DuplicateAndClose ターゲット プロセスのソケット参照を複製してこのプロセスのソケットを閉じます。
パブリック メソッド EndAccept オーバーロードされます。 受信接続の試行を非同期的に受け入れます。
パブリック メソッド EndConnect 保留中の非同期接続要求を終了します。
パブリック メソッド EndDisconnect 保留中の非同期接続解除要求を終了します。
パブリック メソッド EndReceive オーバーロードされます。 保留中の非同期読み込みを終了します。
パブリック メソッド EndReceiveFrom 特定のエンドポイントからの、保留中の非同期読み込みを終了します。
パブリック メソッド EndReceiveMessageFrom 特定のエンドポイントからの、保留中の非同期読み込みを終了します。また、このメソッドは、EndReceiveFrom よりもパケットに関するより多くの情報を示します。
パブリック メソッド EndSend オーバーロードされます。 保留中の非同期送信を終了します。
パブリック メソッド EndSendFile 保留中のファイルの非同期送信を終了します。
パブリック メソッド EndSendTo 特定の位置への、保留中の非同期送信を終了します。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetSocketOption オーバーロードされます。 Socket オプションの値を返します。
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド IOControl オーバーロードされます。 Socket の低レベル操作モードを設定します。
パブリック メソッド Listen Socket を待機状態にします。
パブリック メソッド Poll Socket のステータスを確認します。
パブリック メソッド Receive オーバーロードされます。 バインドされた Socket からデータを受信します。
パブリック メソッド ReceiveFrom オーバーロードされます。 データグラムを受信し、ソース エンドポイントを格納します。
パブリック メソッド ReceiveMessageFrom 指定した SocketFlags を使用し、指定したバイト数のデータを受信して、データ バッファ内の指定した位置に格納します。さらに、エンドポイントとパケット情報を格納します。
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド Select 1 つ以上のソケットのステータスを決定します。
パブリック メソッド Send オーバーロードされます。 接続された Socket にデータを送信します。
パブリック メソッド SendFile オーバーロードされます。 接続された Socket に、ファイルおよびオプション データを同期的に送信します。
パブリック メソッド SendTo オーバーロードされます。 データを特定のエンドポイントに送信します。
パブリック メソッド SetSocketOption オーバーロードされます。 Socket オプションを設定します。
パブリック メソッド Shutdown Socket での送受信を無効にします。
パブリック メソッド ToString  現在の Object を表す String を返します。 ( Object から継承されます。)
プロテクト メソッドプロテクト メソッド
明示的インターフェイスの実装明示的インターフェイスの実装
  名前 説明
インターフェイスの明示的な実装 System.IDisposable.Dispose Socket によって使用されているすべてのリソースを解放します。
参照参照

関連項目

Socket クラス
System.Net.Sockets 名前空間

Socket メンバ

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

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


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド Accept 新しく作成された接続に対して新しい Socket を作成します。
パブリック メソッド BeginAccept オーバーロードされます。 受信接続の試行を受け入れる非同期操作を開始します。
パブリック メソッド BeginConnect オーバーロードされます。 リモート ホスト接続への非同期要求を開始します。
パブリック メソッド BeginDisconnect リモート エンドポイントからの接続解除の非同期要求を開始します。
パブリック メソッド BeginReceive オーバーロードされます。 接続されている Socket からの非同期のデータ受信を開始します。
パブリック メソッド BeginReceiveFrom 指定したネットワーク デバイスから、データの非同期の受信を開始します。
パブリック メソッド BeginReceiveMessageFrom 指定した SocketFlags を使用し、指定したバイト数のデータの非同期受信を開始して、データ バッファ内の指定した位置に格納します。さらに、エンドポイントとパケット情報を格納します。
パブリック メソッド BeginSend オーバーロードされます。 接続されている Socket にデータを非同期的に送信します。
パブリック メソッド BeginSendFile オーバーロードされます。 接続された Socket オブジェクトに、ファイルを非同期的に送信します。
パブリック メソッド BeginSendTo 特定のリモート ホストにデータを非同期的に送信します。
パブリック メソッド Bind Socket をローカル エンドポイントと関連付けます。
パブリック メソッド Close オーバーロードされます。 Socket 接続を閉じ、関連付けられたすべてのリソースを解放します。
パブリック メソッド Connect オーバーロードされます。 リモート ホストへの接続を確立します。
パブリック メソッド Disconnect ソケット接続を閉じ、ソケットを再利用できるようにします。
パブリック メソッド DuplicateAndClose ターゲット プロセスのソケット参照を複製してこのプロセスのソケットを閉じます。
パブリック メソッド EndAccept オーバーロードされます。 受信接続の試行を非同期的に受け入れます。
パブリック メソッド EndConnect 保留中の非同期接続要求を終了します。
パブリック メソッド EndDisconnect 保留中の非同期接続解除要求を終了します。
パブリック メソッド EndReceive オーバーロードされます。 保留中の非同期読み込みを終了します。
パブリック メソッド EndReceiveFrom 特定のエンドポイントからの、保留中の非同期読み込みを終了します。
パブリック メソッド EndReceiveMessageFrom 特定のエンドポイントからの、保留中の非同期読み込みを終了します。また、このメソッドは、EndReceiveFrom よりもパケットに関するより多くの情報を示します。
パブリック メソッド EndSend オーバーロードされます。 保留中の非同期送信を終了します。
パブリック メソッド EndSendFile 保留中のファイルの非同期送信を終了します。
パブリック メソッド EndSendTo 特定の位置への、保留中の非同期送信を終了します。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetSocketOption オーバーロードされます。 Socket オプションの値を返します。
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド IOControl オーバーロードされます。 Socket の低レベル操作モードを設定します。
パブリック メソッド Listen Socket を待機状態にします。
パブリック メソッド Poll Socket のステータスを確認します。
パブリック メソッド Receive オーバーロードされます。 バインドされた Socket からデータを受信します。
パブリック メソッド ReceiveFrom オーバーロードされます。 データグラムを受信し、ソース エンドポイントを格納します。
パブリック メソッド ReceiveMessageFrom 指定した SocketFlags を使用し、指定したバイト数のデータを受信して、データ バッファ内の指定した位置に格納します。さらに、エンドポイントとパケット情報を格納します。
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド Select 1 つ以上のソケットのステータスを決定します。
パブリック メソッド Send オーバーロードされます。 接続された Socket にデータを送信します。
パブリック メソッド SendFile オーバーロードされます。 接続された Socket に、ファイルおよびオプション データを同期的に送信します。
パブリック メソッド SendTo オーバーロードされます。 データを特定のエンドポイントに送信します。
パブリック メソッド SetSocketOption オーバーロードされます。 Socket オプションを設定します。
パブリック メソッド Shutdown Socket での送受信を無効にします。
パブリック メソッド ToString  現在の Object を表す String を返します。 (Object から継承されます。)
プロテクト メソッドプロテクト メソッド
明示的インターフェイスの実装明示的インターフェイスの実装
  名前 説明
インターフェイスの明示的な実装 System.IDisposable.Dispose Socket によって使用されているすべてのリソースを解放します。
参照参照

関連項目

Socket クラス
System.Net.Sockets 名前空間

ソケット socket


ソケット

(socket から転送)

出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2022/05/13 10:29 UTC 版)

ソケット (socket)


socket()

出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2021/04/03 08:34 UTC 版)

「ソケット (BSD)」の記事における「socket()」の解説

socket() は通信の一方の終端を作成し、それを表すファイル記述子を返す。socket() には以下の3つの引数がある。 domain - 生成するソケットのプロトコルファミリを指定する。AF_INET - IPv4 AF_INET6 - IPv6 AF_UNIX - UNIXドメインソケット type - ソケットのタイプ指定。SOCK_STREAM - 信頼性のあるストリーム指向サービス(TCPに対応) SOCK_DGRAM - データグラムサービス(UDPに対応) SOCK_SEQPACKET - SOCK_STREAMとほぼ同じだが、受信したパケットを読み出す際にパケット全体を読み出さないと、残りを破棄する。 SOCK_RAW - IPレベルのプロトコル処理をユーザー側で用意するときに使用 protocol - 通常 0 を指定し、デフォルトの物が選ばれる。トランスポート層のプロトコルは、domain と type で指定されるが(TCPの場合、AF_INET または AF_INET6 と SOCK_STREAM、UDPの場合、同様の AF_ 値と SOCK_DGRAM)、明示的に指定することも可能で、その値は に定義されている。 エラーが発生すると -1 を返す。そうでない場合、新たに確保された記述子を表す整数を返す。 #include #include int socket(int domain, int type, int protocol);

※この「socket()」の解説は、「ソケット (BSD)」の解説の一部です。
「socket()」を含む「ソケット (BSD)」の記事については、「ソケット (BSD)」の概要を参照ください。

ウィキペディア小見出し辞書の「socket」の項目はプログラムで機械的に意味や本文を生成しているため、不適切な項目が含まれていることもあります。ご了承くださいませ。 お問い合わせ。


英和和英テキスト翻訳

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

辞書ショートカット

すべての辞書の索引

「socket」の関連用語

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

   

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



socketのページの著作権

   
実用日本語表現辞典実用日本語表現辞典
Copyright © 2026実用日本語表現辞典 All Rights Reserved.
デジタル大辞泉デジタル大辞泉
(C)Shogakukan Inc.
株式会社 小学館
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.
ダイキン工業ダイキン工業
Copyright (C) 2026 DAIKIN INDUSTRIES, ltd. All Rights Reserved.
ウィキペディアウィキペディア
All text is available under the terms of the GNU Free Documentation License.
この記事は、ウィキペディアのソケット (改訂履歴)の記事を複製、再配布したものにあたり、GNU Free Documentation Licenseというライセンスの下で提供されています。 Weblio辞書に掲載されているウィキペディアの記事も、全てGNU Free Documentation Licenseの元に提供されております。
ウィキペディアウィキペディア
Text is available under GNU Free Documentation License (GFDL).
Weblio辞書に掲載されている「ウィキペディア小見出し辞書」の記事は、Wikipediaのソケット (BSD) (改訂履歴)の記事を複製、再配布したものにあたり、GNU Free Documentation Licenseというライセンスの下で提供されています。

©2026 GRAS Group, Inc.RSS