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 服务器并接收响应。 此示例会阻止直到收到整个页面。
#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);
String^ strRetPage = "";
// 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;
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 );
s->Dispose();
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 );
}
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];
string page = "";
// Create a socket connection with the specified server and port.
using(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;
page = "Default HTML page on " + server + ":\r\n";
// 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);
}
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);
}
}
Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
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]
Dim page As String = ""
' 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.
page = "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
End Class
注解
该 Socket 类为网络通信提供了一组丰富的方法和属性。 该 Socket 类允许你使用枚举中列出的 ProtocolType 任何通信协议执行同步和异步数据传输。
该Socket类遵循异步方法的.NET Framework命名模式。 例如,同步 Receive 方法对应于异步 BeginReceive 和 EndReceive 方法。
如果应用程序在执行过程中只需要一个线程,请使用以下方法,这些方法专为同步操作模式而设计。
如果使用面向连接的协议(如 TCP),则服务器可以使用该方法 Listen 侦听连接。 该方法 Accept 处理任何传入的连接请求并返回一个 Socket 可用于与远程主机通信的数据。 使用此返回 Socket 方法调用 Send 或 Receive 方法。 Bind如果要指定本地 IP 地址和端口号,请在调用该方法之前调用Listen该方法。 如果希望基础服务提供商为你分配免费端口,请使用端口号为零。 如果要连接到侦听主机,请调用 Connect 该方法。 若要传达数据,请调用 Send 或 Receive 方法。
如果使用无连接协议(如 UDP),则根本不需要侦听连接。 调用该方法 ReceiveFrom 以接受任何传入的数据报。 SendTo使用该方法将数据报发送到远程主机。
若要在执行过程中使用单独的线程处理通信,请使用以下方法,这些方法专为异步操作模式而设计。
如果使用面向连接的协议(如 TCP),请使用和SocketBeginConnectEndConnect方法连接到侦听主机。 BeginSend使用和EndSend和BeginReceiveEndReceive方法以异步方式通信数据。 可以使用和 EndAccept. 处理BeginAccept传入的连接请求。
如果使用无连接协议(如 UDP),则可以使用BeginSendTo和EndSendTo发送数据报以及BeginReceiveFromEndReceiveFrom接收数据报。
如果在套接字上执行多个异步操作,则它们不一定按照启动顺序完成。
完成发送和接收数据后,请使用Shutdown该方法禁用 。Socket 调用 Shutdown后,调用 Close 该方法以释放与该 Socket资源关联的所有资源。
该Socket类允许你使用SetSocketOption该方法进行配置Socket。 使用 GetSocketOption 该方法检索这些设置。
备注
如果要编写相对简单的应用程序,并且不需要最佳性能,请考虑使用TcpClient和TcpListenerUdpClient。 这些类为通信提供了更简单、更友好的界面 Socket 。
构造函数
Socket(AddressFamily, SocketType, ProtocolType) |
使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。 |
Socket(SafeSocketHandle) |
为指定的套接字句柄初始化 Socket 类的新实例。 |
Socket(SocketInformation) |
使用 Socket 返回的指定的值初始化 DuplicateAndClose(Int32) 类的新实例。 |
Socket(SocketType, ProtocolType) |
使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。 如果操作系统支持 IPv6,此构造函数将创建双模式套接字;否则,它将创建 IPv4 套接字。 |
属性
AddressFamily |
获取 Socket 的地址族。 |
Available |
获取已经从网络接收且可供读取的数据量。 |
Blocking |
获取或设置一个值,该值指示 Socket 是否处于阻止模式。 |
Connected | |
DontFragment |
获取或设置一个值,该值指定 Socket 是否允许将 Internet 协议 (IP) 数据报分段。 |
DualMode |
获取或设置一个值,该值指定是用于 IPv4 和 IPv6 的 Socket 双模式套接字。 |
EnableBroadcast | |
ExclusiveAddressUse | |
Handle |
获取 Socket 的操作系统句柄。 |
IsBound |
获取一个值,该值指示 Socket 是否绑定到特定本地端口。 |
LingerState |
获取或设置一个值,该值指定 Socket 在尝试发送所有挂起数据时是否延迟关闭套接字。 |
LocalEndPoint |
获取本地终结点。 |
MulticastLoopback |
获取或设置一个值,该值指定传出的多路广播数据包是否传递到发送应用程序。 |
NoDelay | |
OSSupportsIPv4 |
指示基础操作系统和网络适配器是否支持 Internet 协议第 4 版 (IPv4)。 |
OSSupportsIPv6 |
指示基础操作系统和网络适配器是否支持 Internet 协议第 6 版 (IPv6)。 |
OSSupportsUnixDomainSockets |
指示基础操作系统是否支持 Unix 域套接字。 |
ProtocolType |
获取 Socket 的协议类型。 |
ReceiveBufferSize |
获取或设置一个值,它指定 Socket 接收缓冲区的大小。 |
ReceiveTimeout |
获取或设置一个值,该值指定之后同步 Receive 调用将超时的时间长度。 |
RemoteEndPoint |
获取远程终结点。 |
SafeHandle |
获取一个 SafeSocketHandle,它表示当前 Socket 对象封装的套接字句柄。 |
SendBufferSize |
获取或设置一个值,该值指定 Socket 发送缓冲区的大小。 |
SendTimeout |
获取或设置一个值,该值指定之后同步 Send 调用将超时的时间长度。 |
SocketType |
获取 Socket 的类型。 |
SupportsIPv4 |
已过时。
已过时。
已过时。
已过时。
获取一个值,该值指示在当前主机上 IPv4 支持是否可用并且已启用。 |
SupportsIPv6 |
已过时。
已过时。
已过时。
已过时。
获取一个值,该值指示 Framework 对某些已过时的 Dns 成员是否支持 IPv6。 |
Ttl |
获取或设置一个值,指定 Socket 发送的 Internet 协议 (IP) 数据包的生存时间 (TTL) 值。 |
UseOnlyOverlappedIO |
已过时。
获取或设置一个值,该值指定套接字是否只应使用重叠 I/O 模式。 在 .NET 5+ ((包括 .NET Core 版本) )上,该值始终 |
方法
显式接口实现
IDisposable.Dispose() |
此 API 支持产品基础结构,不能在代码中直接使用。 释放由 Socket 使用的所有资源。 |
扩展方法
适用于
线程安全性
此类的实例是线程安全的。