다음을 통해 공유


Socket 생성자

정의

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

오버로드

Name Description
Socket(SafeSocketHandle)

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

Socket(SocketInformation)

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

Socket(SocketType, ProtocolType)

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

Socket(AddressFamily, SocketType, ProtocolType)

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

Socket(SafeSocketHandle)

Source:
Socket.cs
Source:
Socket.cs
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된 데이터에서 수집된 데이터로 인스턴스를 채웁니다. 다른 운영 체제는 해당 속성 및 구성에 대한 소켓 핸들 또는 파일 설명자를 쿼리하기 위한 다양한 수준의 지원을 제공합니다. 결과 Socket 인스턴스의 일부 공용 API는 다음과 같은 ProtocolTypeBlocking운영 체제에 따라 다를 수 있습니다.

적용 대상

Socket(SocketInformation)

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

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

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
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 하나입니다.

예외

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

설명

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

메모

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

메모

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

적용 대상

Socket(AddressFamily, SocketType, ProtocolType)

Source:
Socket.cs
Source:
Socket.cs
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 하나입니다.

예외

addressFamilysocketType조합으로 protocolType 인해 소켓이 잘못되었습니다.

예제

다음 코드 예제에서는 클래스의 인스턴스를 만드는 방법을 보여 줍니다 Socket .

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결과가 발생하는 경우 이 생성자는 을 throw합니다 SocketException.

메모

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

메모

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

추가 정보

적용 대상