다음을 통해 공유


Socket 클래스

Berkeley 소켓 인터페이스를 구현합니다.

네임스페이스: System.Net.Sockets
어셈블리: System(system.dll)

구문

‘선언
Public Class Socket
    Implements IDisposable
‘사용 방법
Dim instance As Socket
public class Socket : IDisposable
public ref class Socket : IDisposable
public class Socket implements IDisposable
public class Socket implements IDisposable

설명

Socket 클래스는 네트워크 통신을 위한 풍부한 메서드 및 속성 집합을 제공합니다. Socket 클래스를 사용하면 ProtocolType 열거형에 나열된 통신 프로토콜을 사용하여 동기 및 비동기 데이터 전송을 수행할 수 있습니다. Socket 클래스는 비동기 메서드에 대해 .NET Framework 명명 패턴을 따릅니다. 예를 들어, 동기 Receive 메서드는 비동기 BeginReceiveEndReceive 메서드에 해당합니다.

실행하는 동안 응용 프로그램에 하나의 스레드만 필요한 경우 동기 작업 모드용으로 디자인된 다음 메서드를 사용합니다.

  • TCP와 같은 연결 지향 프로토콜을 사용하는 경우 서버는 Listen 메서드를 사용하여 연결을 수신할 수 있습니다. Accept 메서드는 들어오는 연결 요청을 처리하고 원격 호스트와 데이터를 주고 받는 데 사용할 수 있는 Socket을 반환합니다. 반환된 해당 Socket을 사용하여 Send 또는 Receive 메서드를 호출합니다. 로컬 IP 주소 및 포트 번호를 지정하려면 Listen 메서드를 호출하기 전에 Bind 메서드를 호출합니다. 내부 서비스 공급자가 사용 가능한 포트를 할당하게 하려면 포트 번호로 0을 사용합니다. 수신 호스트에 연결하려면 Connect 메서드를 호출합니다. 데이터를 보내고 받으려면 Send 또는 Receive 메서드를 호출합니다.

  • UDP와 같은 연결 없는 프로토콜을 사용하는 경우 연결을 수신할 필요가 없습니다. ReceiveFrom 메서드를 호출하여 들어오는 데이터그램을 허용합니다. SendTo 메서드를 사용하여 원격 호스트에 데이터그램을 보냅니다.

실행 중에 별도의 스레드를 사용하여 통신을 처리하려면 비동기 작업 모드용으로 디자인된 다음 메서드를 사용합니다.

  • TCP와 같은 연결 지향 프로토콜을 사용하는 경우 Socket, BeginConnectEndConnect 메서드를 사용하여 수신 호스트와 연결합니다. 데이터를 비동기적으로 주고 받으려면 BeginSendEndSend 또는 BeginReceiveEndReceive 메서드를 사용합니다. 들어오는 연결 요청은 BeginAcceptEndAccept를 사용하여 처리할 수 있습니다.

  • UDP와 같은 연결 없는 프로토콜을 사용하는 경우 BeginSendToEndSendTo를 사용하여 데이터그램을 보내고 BeginReceiveFromEndReceiveFrom을 사용하여 데이터그램을 받을 수 있습니다.

한 소켓에서 여러 개의 비동기 작업을 수행하는 경우 작업이 시작된 순서대로 완료되지 않아도 됩니다.

데이터를 보내고 받는 일이 끝나면 Shutdown 메서드를 사용하여 Socket을 비활성화합니다. Shutdown을 호출한 후에 Close 메서드를 호출하여 Socket과 관련된 모든 리소스를 해제합니다.

Socket 클래스를 사용하면 SetSocketOption 메서드를 통해 Socket을 구성할 수 있습니다. GetSocketOption 메서드를 사용하여 이러한 설정을 검색합니다.

참고

비교적 간단한 응용 프로그램을 작성하거나 최대 성능이 필요하지 않은 경우 TcpClient, TcpListenerUdpClient를 사용해 보십시오. 이러한 클래스는 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 보안

  • SocketPermission  나가는 연결을 설정하거나 들어오는 요청을 받아들이는 데 필요한 권한입니다.

상속 계층 구조

System.Object
  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에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Socket 멤버
System.Net.Sockets 네임스페이스