Socket 생성자

정의

Socket 클래스의 새 인스턴스를 초기화합니다.

오버로드

Socket(SafeSocketHandle)

지정된 소켓 핸들에 대한 Socket 클래스의 새 인스턴스를 초기화합니다.

Socket(SocketInformation)

Socket에서 반환된 특정 값을 사용하여 DuplicateAndClose(Int32) 클래스의 새 인스턴스를 초기화합니다.

Socket(SocketType, ProtocolType)

지정된 소켓 종류 및 프로토콜을 사용하여 Socket 클래스의 새 인스턴스를 초기화합니다. 운영 체제에서 IPv6을 지원하는 경우 이 생성자는 이중 모드 소켓을 만듭니다. 그렇지 않으면 IPv4 소켓을 만듭니다.

Socket(AddressFamily, SocketType, ProtocolType)

지정된 주소 패밀리, 소켓 종류 및 프로토콜을 사용하여 Socket 클래스의 새 인스턴스를 초기화합니다.

Socket(SafeSocketHandle)

Source:
Socket.cs
Source:
Socket.cs
Source:
Socket.cs

지정된 소켓 핸들에 대한 Socket 클래스의 새 인스턴스를 초기화합니다.

public:
 Socket(System::Net::Sockets::SafeSocketHandle ^ handle);
public Socket (System.Net.Sockets.SafeSocketHandle handle);
new System.Net.Sockets.Socket : System.Net.Sockets.SafeSocketHandle -> System.Net.Sockets.Socket
Public Sub New (handle As SafeSocketHandle)

매개 변수

handle
SafeSocketHandle

Socket 개체가 캡슐화할 소켓의 소켓 핸들입니다.

예외

handlenull입니다.

handle이 잘못되었습니다.

handle이 소켓이 아니거나 소켓 정보에 액세스할 수 없습니다.

설명

이 메서드는 Socket 제공된 SafeSocketHandle에서 수집된 데이터로 instance 채웁니다. 다른 운영 체제는 해당 속성 및 구성에 대한 소켓 핸들 또는 파일 설명자를 쿼리하기 위한 다양한 수준의 지원을 제공합니다. 결과 Socket instance 일부 공용 API는 및 Blocking와 같은 ProtocolType 운영 체제에 따라 다를 수 있습니다.

적용 대상

Socket(SocketInformation)

Source:
Socket.cs
Source:
Socket.cs
Source:
Socket.cs

Socket에서 반환된 특정 값을 사용하여 DuplicateAndClose(Int32) 클래스의 새 인스턴스를 초기화합니다.

public:
 Socket(System::Net::Sockets::SocketInformation socketInformation);
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public Socket (System.Net.Sockets.SocketInformation socketInformation);
public Socket (System.Net.Sockets.SocketInformation socketInformation);
[<System.Runtime.Versioning.SupportedOSPlatform("windows")>]
new System.Net.Sockets.Socket : System.Net.Sockets.SocketInformation -> System.Net.Sockets.Socket
new System.Net.Sockets.Socket : System.Net.Sockets.SocketInformation -> System.Net.Sockets.Socket
Public Sub New (socketInformation As SocketInformation)

매개 변수

socketInformation
SocketInformation

DuplicateAndClose(Int32)에서 반환된 소켓 정보입니다.

특성

설명

각 호출에 Socket 대한 인수와 동일한 바이트 배열을 사용하여 생성자를 여러 번 호출하는 경우 동일한 기본 소켓을 사용하여 여러 관리 Socket되는 s를 만듭니다. 이 관행은 매우 권장되지 않습니다.

적용 대상

Socket(SocketType, ProtocolType)

Source:
Socket.cs
Source:
Socket.cs
Source:
Socket.cs

지정된 소켓 종류 및 프로토콜을 사용하여 Socket 클래스의 새 인스턴스를 초기화합니다. 운영 체제에서 IPv6을 지원하는 경우 이 생성자는 이중 모드 소켓을 만듭니다. 그렇지 않으면 IPv4 소켓을 만듭니다.

public:
 Socket(System::Net::Sockets::SocketType socketType, System::Net::Sockets::ProtocolType protocolType);
public Socket (System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType);
new System.Net.Sockets.Socket : System.Net.Sockets.SocketType * System.Net.Sockets.ProtocolType -> System.Net.Sockets.Socket
Public Sub New (socketType As SocketType, protocolType As ProtocolType)

매개 변수

socketType
SocketType

SocketType 값 중 하나입니다.

protocolType
ProtocolType

ProtocolType 값 중 하나입니다.

예외

protocolTypesocketType 조합으로 인해 잘못된 소켓이 생성됩니다.

설명

매개 변수는 socketType 클래스의 형식을 Socket 지정하고 매개 변수는 protocolType 에서 Socket사용하는 프로토콜을 지정합니다. 두 매개 변수는 독립적이지 않습니다. 종종 형식은 Socket 프로토콜에서 암시적입니다. 형식과 프로토콜 형식의 Socket 조합으로 인해 잘못된 Socket가 발생하면 이 생성자는 을 SocketExceptionthrow합니다.

참고

이 생성자가 를 throw하는 SocketException경우 속성을 사용하여 SocketException.ErrorCode 특정 오류 코드를 가져옵니다. 이 코드를 가져온 후 오류에 대한 자세한 설명 은 Windows 소켓 버전 2 API 오류 코드 설명서를 참조하세요.

참고

애플리케이션에 네트워크 추적을 사용하도록 설정하면 이 멤버에서 추적 정보를 출력합니다. 자세한 내용은 .NET Framework 네트워크 추적을 참조하세요.

적용 대상

Socket(AddressFamily, SocketType, ProtocolType)

Source:
Socket.cs
Source:
Socket.cs
Source:
Socket.cs

지정된 주소 패밀리, 소켓 종류 및 프로토콜을 사용하여 Socket 클래스의 새 인스턴스를 초기화합니다.

public:
 Socket(System::Net::Sockets::AddressFamily addressFamily, System::Net::Sockets::SocketType socketType, System::Net::Sockets::ProtocolType protocolType);
public Socket (System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType);
new System.Net.Sockets.Socket : System.Net.Sockets.AddressFamily * System.Net.Sockets.SocketType * System.Net.Sockets.ProtocolType -> System.Net.Sockets.Socket
Public Sub New (addressFamily As AddressFamily, socketType As SocketType, protocolType As ProtocolType)

매개 변수

addressFamily
AddressFamily

AddressFamily 값 중 하나입니다.

socketType
SocketType

SocketType 값 중 하나입니다.

protocolType
ProtocolType

ProtocolType 값 중 하나입니다.

예외

addressFamily, socketTypeprotocolType을 조합했을 때 소켓이 잘못된 경우

예제

다음 코드 예제를 만드는 방법을 보여 줍니다는 클래스의 Socket instance 합니다.

#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" ) );
}
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"));
   }
 }
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
End Class

설명

매개 변수는 addressFamily 클래스에서 사용하는 주소 지정 체계 Socket 를 지정하고, socketType 매개 변수는 클래스의 형식을 Socket 지정하고, 매개 변수는 protocolType 에서 Socket사용하는 프로토콜을 지정합니다. 세 가지 매개 변수는 독립적이지 않습니다. 일부 주소 패밀리는 함께 사용할 수 있는 프로토콜을 제한하며, 종종 형식이 Socket 프로토콜에서 암시적입니다. 주소 패밀리, Socket 형식 및 프로토콜 형식의 조합으로 인해 잘못된 Socket가 발생하는 경우 이 생성자는 을 SocketExceptionthrow합니다.

참고

이 생성자가 를 throw하는 SocketException경우 속성을 사용하여 SocketException.ErrorCode 특정 오류 코드를 가져옵니다. 이 코드를 가져온 후 오류에 대한 자세한 설명 은 Windows 소켓 버전 2 API 오류 코드 설명서를 참조하세요.

참고

애플리케이션에 네트워크 추적을 사용하도록 설정하면 이 멤버에서 추적 정보를 출력합니다. 자세한 내용은 .NET Framework 네트워크 추적을 참조하세요.

추가 정보

적용 대상