Socket 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
Berkeley 소켓 인터페이스를 구현합니다.
public ref class Socket : IDisposable
public class Socket : IDisposable
type Socket = class
interface IDisposable
Public Class Socket
Implements IDisposable
- 상속
-
Socket
- 구현
예제
다음 예제에서는 클래스를 Socket 사용하여 데이터를 HTTP 서버로 보내고 표준 출력에 ASCII 응답을 인쇄하는 방법을 보여 줍니다. 다음은 전체 페이지를 받을 때까지 호출 스레드를 차단하는 예제입니다.
private static void SendHttpRequest(Uri? uri = null, int port = 80)
{
uri ??= new Uri("http://example.com");
// Construct a minimalistic HTTP/1.1 request
byte[] requestBytes = Encoding.ASCII.GetBytes(@$"GET {uri.AbsoluteUri} HTTP/1.0
Host: {uri.Host}
Connection: Close
");
// Create and connect a dual-stack socket
using Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
socket.Connect(uri.Host, port);
// Send the request.
// For the tiny amount of data in this example, the first call to Send() will likely deliver the buffer completely,
// however this is not guaranteed to happen for larger real-life buffers.
// The best practice is to iterate until all the data is sent.
int bytesSent = 0;
while (bytesSent < requestBytes.Length)
{
bytesSent += socket.Send(requestBytes, bytesSent, requestBytes.Length - bytesSent, SocketFlags.None);
}
// Do minimalistic buffering assuming ASCII response
byte[] responseBytes = new byte[256];
char[] responseChars = new char[256];
while (true)
{
int bytesReceived = socket.Receive(responseBytes);
// Receiving 0 bytes means EOF has been reached
if (bytesReceived == 0) break;
// Convert byteCount bytes to ASCII characters using the 'responseChars' buffer as destination
int charCount = Encoding.ASCII.GetChars(responseBytes, 0, bytesReceived, responseChars, 0);
// Print the contents of the 'responseChars' buffer to Console.Out
Console.Out.Write(responseChars, 0, charCount);
}
}
다음 예제에서는 작업 기반 비동기 API를 사용하는 동시에 비동기 메서드에 전달하여 CancellationToken 전체 작업을 취소할 수 있도록 하는 동일한 HTTP GET 시나리오를 보여 줍니다.
Tip
Socket일반적으로 힙에 할당된 반환을 CancellationTokenTask사용하지 않는 비동기 메서드입니다. 취소 가능한 오버로드는 항상 ValueTask반환됩니다. 이를 사용하면 고성능 코드에서 할당을 줄이는 데 도움이 됩니다.
private static async Task SendHttpRequestAsync(Uri? uri = null, int port = 80, CancellationToken cancellationToken = default)
{
uri ??= new Uri("http://example.com");
// Construct a minimalistic HTTP/1.1 request
byte[] requestBytes = Encoding.ASCII.GetBytes(@$"GET {uri.AbsoluteUri} HTTP/1.1
Host: {uri.Host}
Connection: Close
");
// Create and connect a dual-stack socket
using Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
await socket.ConnectAsync(uri.Host, port, cancellationToken);
// Send the request.
// For the tiny amount of data in this example, the first call to SendAsync() will likely deliver the buffer completely,
// however this is not guaranteed to happen for larger real-life buffers.
// The best practice is to iterate until all the data is sent.
int bytesSent = 0;
while (bytesSent < requestBytes.Length)
{
bytesSent += await socket.SendAsync(requestBytes.AsMemory(bytesSent), SocketFlags.None);
}
// Do minimalistic buffering assuming ASCII response
byte[] responseBytes = new byte[256];
char[] responseChars = new char[256];
while (true)
{
int bytesReceived = await socket.ReceiveAsync(responseBytes, SocketFlags.None, cancellationToken);
// Receiving 0 bytes means EOF has been reached
if (bytesReceived == 0) break;
// Convert byteCount bytes to ASCII characters using the 'responseChars' buffer as destination
int charCount = Encoding.ASCII.GetChars(responseBytes, 0, bytesReceived, responseChars, 0);
// Print the contents of the 'responseChars' buffer to Console.Out
await Console.Out.WriteAsync(responseChars.AsMemory(0, charCount), cancellationToken);
}
}
설명
이 API에 대한 자세한 내용은 소켓에 대한 추가 API 비고를 참조하세요.
생성자
| Name | Description |
|---|---|
| Socket(AddressFamily, SocketType, ProtocolType) |
지정된 주소 패밀리, 소켓 유형 및 프로토콜을 사용하여 클래스의 Socket 새 인스턴스를 초기화합니다. |
| Socket(SafeSocketHandle) |
지정된 소켓 핸들에 대한 클래스의 Socket 새 인스턴스를 초기화합니다. |
| Socket(SocketInformation) |
에서 반환Socket된 지정된 값을 사용하여 클래스의 DuplicateAndClose(Int32) 새 인스턴스를 초기화합니다. |
| Socket(SocketType, ProtocolType) |
지정된 소켓 형식 및 프로토콜을 Socket 사용하여 클래스의 새 인스턴스를 초기화합니다. 운영 체제에서 IPv6을 지원하는 경우 이 생성자는 이중 모드 소켓을 만듭니다. 그렇지 않으면 IPv4 소켓을 만듭니다. |
속성
| Name | Description |
|---|---|
| AddressFamily |
의 주소 패밀리를 Socket가져옵니다. |
| Available |
네트워크에서 수신되어 읽을 수 있는 데이터의 양을 가져옵니다. |
| Blocking |
차단 모드에 있는지 여부를 Socket 나타내는 값을 가져오거나 설정합니다. |
| Connected |
마지막 Socket 또는 Send 작업을 기준으로 원격 호스트에 연결되어 있는지 여부를 Receive 나타내는 값을 가져옵니다. |
| DontFragment |
IP(인터넷 프로토콜) 데이터그램을 조각화할 수 있는지 여부를 Socket 지정하는 값을 가져오거나 설정합니다. |
| DualMode |
IPv4 및 IPv6 모두에 사용되는 이중 모드 소켓인지 여부를 Socket 지정하는 값을 가져오거나 설정합니다. |
| EnableBroadcast | |
| ExclusiveAddressUse |
하나의 프로세스만 포트에 Socket 바인딩할 수 있는지 여부를 나타내는 값을 가져오거나 설정합니다. |
| Handle |
에 대한 운영 체제 핸들을 Socket가져옵니다. |
| IsBound |
특정 로컬 포트에 Socket 바인딩되는지 여부를 나타내는 값을 가져옵니다. |
| LingerState |
보류 중인 모든 데이터를 보내기 위해 소켓 닫기를 지연할지 여부를 Socket 지정하는 값을 가져오거나 설정합니다. |
| LocalEndPoint |
로컬 엔드포인트를 가져옵니다. |
| MulticastLoopback |
보내는 멀티캐스트 패킷이 보내는 애플리케이션에 배달되는지 여부를 지정하는 값을 가져오거나 설정합니다. |
| NoDelay |
스트림 Boolean 이 Nagle 알고리즘을 Socket 사용하는지 여부를 지정하는 값을 가져오거나 설정합니다. |
| OSSupportsIPv4 |
기본 운영 체제 및 네트워크 어댑터가 IPv4(인터넷 프로토콜 버전 4)를 지원하는지 여부를 나타냅니다. |
| OSSupportsIPv6 |
기본 운영 체제 및 네트워크 어댑터가 IPv6(인터넷 프로토콜 버전 6)을 지원하는지 여부를 나타냅니다. |
| OSSupportsUnixDomainSockets |
기본 운영 체제가 Unix 도메인 소켓을 지원하는지 여부를 나타냅니다. |
| ProtocolType |
의 프로토콜 형식을 가져옵니다 Socket. |
| ReceiveBufferSize |
의 수신 버퍼 Socket크기를 지정하는 값을 가져오거나 설정합니다. |
| ReceiveTimeout |
동기 Receive 호출 시간이 초과되는 시간을 지정하는 값을 가져오거나 설정합니다. |
| RemoteEndPoint |
원격 엔드포인트를 가져옵니다. |
| SafeHandle |
SafeSocketHandle 현재 Socket 개체가 캡슐화하는 소켓 핸들을 나타내는 값을 가져옵니다. |
| SendBufferSize |
의 송신 버퍼 Socket크기를 지정하는 값을 가져오거나 설정합니다. |
| SendTimeout |
동기 Send 호출 시간이 초과되는 시간을 지정하는 값을 가져오거나 설정합니다. |
| SocketType |
Socket형식을 가져옵니다. |
| SupportsIPv4 |
사용되지 않음.
사용되지 않음.
사용되지 않음.
현재 호스트에서 IPv4 지원을 사용할 수 있고 사용할 수 있는지 여부를 나타내는 값을 가져옵니다. |
| SupportsIPv6 |
사용되지 않음.
사용되지 않음.
사용되지 않음.
프레임워크가 사용되지 Dns 않는 특정 멤버에 대해 IPv6을 지원하는지 여부를 나타내는 값을 가져옵니다. |
| Ttl |
에서 보낸 SocketIP(인터넷 프로토콜) 패킷의 TTL(Time To Live) 값을 지정하는 값을 가져오거나 설정합니다. |
| UseOnlyOverlappedIO |
사용되지 않음.
소켓이 겹치는 I/O 모드만 사용해야 하는지 여부를 지정하는 값을 가져오거나 설정합니다. .NET 5 이상(.NET Core 버전 포함)에서 값은 항상 |
메서드
명시적 인터페이스 구현
| Name | Description |
|---|---|
| IDisposable.Dispose() |
이 API는 제품 인프라를 지원하며 코드에서 직접 사용되지 않습니다. 에서 사용하는 모든 리소스를 Socket해제합니다. |
확장명 메서드
적용 대상
스레드 보안
인스턴스에서 동시에 Socket 송신 및 수신 작업을 수행하는 것이 안전하지만 여러 송신 또는 여러 수신 호출을 동시에 발급하는 것은 권장되지 않습니다. 기본 플랫폼 구현에 따라 대규모 또는 다중 버퍼 송신 또는 수신에 대한 의도하지 않은 데이터 인터리빙이 발생할 수 있습니다.