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);
}
}
下一個範例示範相同的 HTTP GET 案例,使用工作型異步 API,同時將轉送 CancellationToken 至異步方法,讓整個作業可取消。
提示
Socket不採用 CancellationToken 的異步方法通常會傳回 Task,其配置於堆積上。 可取消的多載一律 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 的詳細資訊,請參閱 Socket 的補充 API 備註。
Socket(Address |
使用指定的通訊協定家族 (Family)、通訊端類型和通訊協定,初始化 Socket 類別的新執行個體。 |
Socket(Safe |
針對指定的通訊端控制代碼,將 Socket 類別的新執行個體初始化。 |
Socket(Socket |
使用從 Socket 傳回的指定值,初始化 DuplicateAndClose(Int32) 類別的新執行個體。 |
Socket(Socket |
使用指定的通訊端類型和通訊協定,初始化 Socket 類別的新執行個體。 如果操作系統支援 IPv6,此建構函式會建立雙模式套接字;否則,它會建立 IPv4 套接字。 |
Address |
取得 Socket 的通訊協定家族 (Family)。 |
Available |
取得已從網路接收且可供讀取的資料量。 |
Blocking |
取得或設定值,指出 Socket 是否處於區塊模式。 |
Connected | |
Dont |
取得或設定值,此值指定 Socket 是否允許將網際網路通訊協定 (IP) 資料包分割為片段。 |
Dual |
取得或設定值,指定 是否 Socket 為用於IPv4和IPv6的雙模式套接字。 |
Enable |
|
Exclusive |
|
Handle |
取得 Socket 的作業系統處理。 |
Is |
取得值,指出 Socket 是否繫結至特定的本機通訊埠。 |
Linger |
取得或設定值,指定 Socket 是否會延遲關閉通訊端,以嘗試傳送所有暫止資料。 |
Local |
取得本機端點。 |
Multicast |
取得或設定值,指定輸出多點傳送封包是否會傳遞至傳送應用程式。 |
No |
|
OSSupports |
指出基礎作業系統和網路配置器是否支援網際網路通訊協定第 4 版 (IPv4)。 |
OSSupports |
指出基礎作業系統和網路配置器是否支援網際網路通訊協定第 6 版 (IPv6)。 |
OSSupports |
指出底層作業系統是否支援 Unix 網域通訊端。 |
Protocol |
取得 Socket 的通訊協定 (Protocol) 類型。 |
Receive |
取得或設定值,指定 Socket 之接收緩衝區的大小。 |
Receive |
取得或設定值,指定同步 Receive 呼叫逾時之前的時間長度。 |
Remote |
取得遠端端點。 |
Safe |
取得 SafeSocketHandle,表示目前 Socket 物件所封裝的通訊端控制代碼。 |
Send |
取得或設定值,指定 Socket 之傳送緩衝區的大小。 |
Send |
取得或設定值,指定同步 Send 呼叫逾時之前的時間長度。 |
Socket |
取得 Socket 的類型。 |
Supports |
已淘汰.
已淘汰.
已淘汰.
取得值,指出 IPv4 支援是否可用並在目前的主機上啟用。 |
Supports |
已淘汰.
已淘汰.
已淘汰.
取得值,指出「架構」是否對某些已過時 Dns 成員支援 IPv6。 |
Ttl |
取得或設定值,指定 Socket 傳送之網際網路通訊協定 (IP) 封包的存留時間 (TTL) 值。 |
Use |
已淘汰.
取得或設定值,指定套接字是否應該只使用重疊 I/O 模式。 在 .NET 5+ (上,包括 .NET Core 版本) ,此值一律 |
IDisposable. |
此 API 支援此產品基礎結構,但無法直接用於程式碼之中。 釋放 Socket 所使用的所有資源。 |
產品 | 版本 |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.3, 1.4, 1.6, 2.0, 2.1 |
UWP | 10.0 |
在實例上 Socket 同時執行傳送和接收作業是安全的,但不建議同時發出多個傳送或多個接收呼叫。 視基礎平台實作而定,這可能會導致大型或多緩衝區傳送或接收的非預期數據交錯。