Socket.ReceiveFrom Socket.ReceiveFrom Socket.ReceiveFrom Socket.ReceiveFrom Method

定义

接收数据报并存储源终结点。Receives a datagram and stores the source endpoint.

重载

ReceiveFrom(Byte[], SocketFlags, EndPoint) ReceiveFrom(Byte[], SocketFlags, EndPoint) ReceiveFrom(Byte[], SocketFlags, EndPoint)

使用指定的 SocketFlags 将数据报接收到数据缓冲区并存储终结点。Receives a datagram into the data buffer, using the specified SocketFlags, and stores the endpoint.

ReceiveFrom(Byte[], EndPoint) ReceiveFrom(Byte[], EndPoint) ReceiveFrom(Byte[], EndPoint) ReceiveFrom(Byte[], EndPoint)

将数据报接收到数据缓冲区并存储终结点。Receives a datagram into the data buffer and stores the endpoint.

ReceiveFrom(Byte[], Int32, SocketFlags, EndPoint) ReceiveFrom(Byte[], Int32, SocketFlags, EndPoint) ReceiveFrom(Byte[], Int32, SocketFlags, EndPoint)

使用指定的 SocketFlags 将指定的字节数接收到数据缓冲区并存储终结点。Receives the specified number of bytes into the data buffer, using the specified SocketFlags, and stores the endpoint.

ReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint) ReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint) ReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint)

使用指定的 SocketFlags 将指定的数据字节数接收到数据缓冲区的指定位置,并存储终结点。Receives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint.

ReceiveFrom(Byte[], SocketFlags, EndPoint) ReceiveFrom(Byte[], SocketFlags, EndPoint) ReceiveFrom(Byte[], SocketFlags, EndPoint)

使用指定的 SocketFlags 将数据报接收到数据缓冲区并存储终结点。Receives a datagram into the data buffer, using the specified SocketFlags, and stores the endpoint.

public:
 int ReceiveFrom(cli::array <System::Byte> ^ buffer, System::Net::Sockets::SocketFlags socketFlags, System::Net::EndPoint ^ % remoteEP);
public int ReceiveFrom (byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP);
member this.ReceiveFrom : byte[] * System.Net.Sockets.SocketFlags *  -> int

参数

buffer
Byte[]

Byte 类型的数组,它是存储接收到的数据的位置。An array of type Byte that is the storage location for the received data.

socketFlags
SocketFlags SocketFlags SocketFlags SocketFlags

SocketFlags 值的按位组合。A bitwise combination of the SocketFlags values.

remoteEP
EndPoint EndPoint EndPoint EndPoint

通过引用传递的 EndPoint,表示远程服务器。An EndPoint, passed by reference, that represents the remote server.

返回

收到的字节数。The number of bytes received.

异常

buffernullbuffer is null.

- 或 --or- remoteEPnullremoteEP is null.

尝试访问套接字时出错。An error occurred when attempting to access the socket.

调用堆栈中的调用方没有所需的权限。A caller in the call stack does not have the required permissions.

示例

下面的代码示例从远程主机接收无连接的数据报。The following code example receives a connectionless datagram from a remote host. SocketFlags 传递给ReceiveFrom方法。SocketFlags are passed to the ReceiveFrom method.

static void ReceiveFrom2()
{
   IPHostEntry^ hostEntry = Dns::Resolve( Dns::GetHostName() );
   IPEndPoint^ endPoint = gcnew IPEndPoint( hostEntry->AddressList[ 0 ],11000 );

   Socket^ s = gcnew Socket( endPoint->Address->AddressFamily,
      SocketType::Dgram,
      ProtocolType::Udp );
   
   // Creates an IpEndPoint to capture the identity of the sending host.
   IPEndPoint^ sender = gcnew IPEndPoint( IPAddress::Any,0 );
   EndPoint^ senderRemote = safe_cast<EndPoint^>(sender);
   
   // Binding is required with ReceiveFrom calls.
   s->Bind( endPoint );

   array<Byte>^ msg = gcnew array<Byte>(256);
   Console::WriteLine( "Waiting to receive datagrams from client..." );
   // This call blocks. 
   s->ReceiveFrom( msg, SocketFlags::None, senderRemote );
   s->Close();
}
public static void ReceiveFrom2()
{
    IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
    IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);

    Socket s = new Socket(endPoint.Address.AddressFamily,
        SocketType.Dgram,
        ProtocolType.Udp);
    
    // Creates an IpEndPoint to capture the identity of the sending host.
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint senderRemote = (EndPoint)sender;
    
    // Binding is required with ReceiveFrom calls.
    s.Bind(endPoint);
    
    byte[] msg = new Byte[256];
    Console.WriteLine ("Waiting to receive datagrams from client...");
    // This call blocks. 
    s.ReceiveFrom(msg, SocketFlags.None, ref senderRemote);
    s.Close();
}
Public Shared Sub ReceiveFrom2() 
    Dim hostEntry As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
    Dim endPoint As New IPEndPoint(hostEntry.AddressList(0), 11000)
    
    Dim s As New Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
    
    ' Creates an IpEndPoint to capture the identity of the sending host.
    Dim sender As New IPEndPoint(IPAddress.Any, 0)
    Dim senderRemote As EndPoint = CType(sender, EndPoint)
    
    ' Binding is required with ReceiveFrom calls.
    s.Bind(endPoint)
    
    Dim msg() As Byte = New [Byte](255) {}
    Console.WriteLine("Waiting to receive datagrams from client...")
    ' This call blocks. 
    s.ReceiveFrom(msg, SocketFlags.None, senderRemote)
    s.Close()

End Sub 'ReceiveFrom2

注解

ReceiveFrom方法将数据读入buffer参数,返回已成功读取的字节数和捕获从其发送数据的远程主机终结点。The ReceiveFrom method reads data into the buffer parameter, returns the number of bytes successfully read, and captures the remote host endpoint from which the data was sent. 此方法很有用,如果你想要从未知的主机或多个主机接收无连接的数据报。This method is useful if you intend to receive connectionless datagrams from an unknown host or multiple hosts.

此重载仅要求您提供接收缓冲区,所需SocketFlags,和一个EndPoint表示远程主机。This overload only requires you to provide a receive buffer, the necessary SocketFlags, and an EndPoint that represents the remote host. 偏移量默认值为 0 并默认大小为缓冲区参数的长度。The offset defaults to 0 and the size defaults to the length of the buffer parameter.

备注

然后再调用ReceiveFrom,则必须显式将绑定Socket到本地终结点使用Bind方法。Before calling ReceiveFrom, you must explicitly bind the Socket to a local endpoint using the Bind method. 如果不,这样做ReceiveFrom将引发SocketExceptionIf you do not, ReceiveFrom will throw a SocketException.

使用无连接协议时,ReceiveFrom将读取第一个排队数据报接收到的本地网络缓冲区。With connectionless protocols, ReceiveFrom will read the first enqueued datagram received into the local network buffer. 如果你收到的数据报大于的大小buffer,则ReceiveFrom方法将填充buffer太多的是,且引发的消息与SocketExceptionIf the datagram you receive is larger than the size of buffer, the ReceiveFrom method will fill buffer with as much of the message as is possible, and throw a SocketException. 如果使用的不可靠的协议,则多余的数据将丢失。If you are using an unreliable protocol, the excess data will be lost. 如果您使用的是可靠的协议,多余的数据将保留由服务提供商可以通过调用检索它ReceiveFrom方法使用一个足够大的缓冲区。If you are using a reliable protocol, the excess data will be retained by the service provider and you can retrieve it by calling the ReceiveFrom method with a large enough buffer.

如果没有任何数据可供读取,ReceiveFrom方法将阻塞,直到有可用数据。If no data is available for reading, the ReceiveFrom method will block until data is available. 如果您是在非阻止模式下,并且没有在可用的数据中的协议堆栈缓冲区ReceiveFrom方法将立即完成并引发SocketExceptionIf you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the ReceiveFrom method will complete immediately and throw a SocketException. 可以使用Available属性来确定数据是否可供读取。You can use the Available property to determine if data is available for reading. Available为非零,重试该接收操作。When Available is non-zero, retry the receive operation.

尽管ReceiveFrom适用于无连接协议,你可以使用面向连接的协议也。Although ReceiveFrom is intended for connectionless protocols, you can use a connection-oriented protocol as well. 如果你选择这样做,则必须首先可以建立远程主机连接通过调用Connect方法,或接受传入的远程主机连接,通过调用Accept方法。If you choose to do so, you must first either establish a remote host connection by calling the Connect method or accept an incoming remote host connection by calling the Accept method. 如果没有建立或接受连接,然后调用ReceiveFrom方法时,将获取SocketExceptionIf you do not establish or accept a connection before calling the ReceiveFrom method, you will get a SocketException. 您还可以建立默认远程主机之前调用的无连接协议ReceiveFrom方法。You can also establish a default remote host for a connectionless protocol prior to calling the ReceiveFrom method. 在这些情况下,任一ReceiveFrom方法将忽略remoteEP参数和仅接收来自连接的数据或默认远程主机。In either of these cases, the ReceiveFrom method will ignore the remoteEP parameter and only receive data from the connected or default remote host.

使用面向连接的套接字ReceiveFrom将读取的数据,可最大的大小bufferWith connection-oriented sockets, ReceiveFrom will read as much data as is available up to the size of buffer. 如果远程主机关闭Socket与连接Shutdown收到了方法,并且所有可用数据,ReceiveFrom方法将立即完成并返回零字节。If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been Received, the ReceiveFrom method will complete immediately and return zero bytes.

备注

如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

AddressFamilyEndPoint中使用ReceiveFrom必须与匹配AddressFamilyEndPoint中使用SendToThe AddressFamily of the EndPoint used in ReceiveFrom needs to match the AddressFamily of the EndPoint used in SendTo.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

安全性

SocketPermission
用于接受来自网络的连接。for accepting connections from the network. 关联枚举:AcceptAssociated enumeration: Accept.

另请参阅

ReceiveFrom(Byte[], EndPoint) ReceiveFrom(Byte[], EndPoint) ReceiveFrom(Byte[], EndPoint) ReceiveFrom(Byte[], EndPoint)

将数据报接收到数据缓冲区并存储终结点。Receives a datagram into the data buffer and stores the endpoint.

public:
 int ReceiveFrom(cli::array <System::Byte> ^ buffer, System::Net::EndPoint ^ % remoteEP);
public int ReceiveFrom (byte[] buffer, ref System.Net.EndPoint remoteEP);
member this.ReceiveFrom : byte[] *  -> int
Public Function ReceiveFrom (buffer As Byte(), ByRef remoteEP As EndPoint) As Integer

参数

buffer
Byte[]

类型 Byte 的数组,它是所接受的数据的存储位置。An array of type Byte that is the storage location for received data.

remoteEP
EndPoint EndPoint EndPoint EndPoint

通过引用传递的 EndPoint,表示远程服务器。An EndPoint, passed by reference, that represents the remote server.

返回

收到的字节数。The number of bytes received.

异常

buffernullbuffer is null.

- 或 --or- remoteEPnullremoteEP is null.

尝试访问套接字时出错。An error occurred when attempting to access the socket.

调用堆栈中的调用方没有所需的权限。A caller in the call stack does not have the required permissions.

示例

下面的代码示例从远程主机接收无连接的数据报。The following code example receives a connectionless datagram from a remote host.

static void ReceiveFrom1()
{
   IPHostEntry^ hostEntry = Dns::Resolve( Dns::GetHostName() );
   IPEndPoint^ endPoint = gcnew IPEndPoint( hostEntry->AddressList[ 0 ],11000 );

   Socket^ s = gcnew Socket( endPoint->Address->AddressFamily,
      SocketType::Dgram,
      ProtocolType::Udp );
   
   // Creates an IPEndPoint to capture the identity of the sending host.
   IPEndPoint^ sender = gcnew IPEndPoint( IPAddress::Any,0 );
   EndPoint^ senderRemote = safe_cast<EndPoint^>(sender);
   
   // Binding is required with ReceiveFrom calls.
   s->Bind( endPoint );

   array<Byte>^ msg = gcnew array<Byte>(256);
   Console::WriteLine( "Waiting to receive datagrams from client..." );
   
   // This call blocks. 
   s->ReceiveFrom( msg, senderRemote );
   s->Close();
}
public static void ReceiveFrom1()
{
    IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
    IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);

    Socket s = new Socket(endPoint.Address.AddressFamily,
        SocketType.Dgram,
        ProtocolType.Udp);
  
    // Creates an IPEndPoint to capture the identity of the sending host.
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint senderRemote = (EndPoint)sender;
    
    // Binding is required with ReceiveFrom calls.
    s.Bind(endPoint);
    
    byte[] msg = new Byte[256];
    Console.WriteLine ("Waiting to receive datagrams from client...");
    
    // This call blocks. 
    s.ReceiveFrom(msg, ref senderRemote);
    s.Close();
}
Public Shared Sub ReceiveFrom1() 
    Dim hostEntry As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
    Dim endPoint As New IPEndPoint(hostEntry.AddressList(0), 11000)
    
    Dim s As New Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
    
    ' Creates an IPEndPoint to capture the identity of the sending host.
    Dim sender As New IPEndPoint(IPAddress.Any, 0)
    Dim senderRemote As EndPoint = CType(sender, EndPoint)
    
    ' Binding is required with ReceiveFrom calls.
    s.Bind(endPoint)
    
    Dim msg() As Byte = New [Byte](255) {}
    Console.WriteLine("Waiting to receive datagrams from client...")
    
    ' This call blocks. 
    s.ReceiveFrom(msg, senderRemote)
    s.Close()

End Sub 'ReceiveFrom1

注解

ReceiveFrom方法将数据读入buffer参数,返回已成功读取的字节数和捕获从其发送数据的远程主机终结点。The ReceiveFrom method reads data into the buffer parameter, returns the number of bytes successfully read, and captures the remote host endpoint from which the data was sent. 此方法很有用,如果你想要从未知的主机或多个主机接收无连接的数据报。This method is useful if you intend to receive connectionless datagrams from an unknown host or multiple hosts.

此重载仅要求您提供一个接收buffer,和一个EndPoint表示远程主机。This overload only requires you to provide a receive buffer, and an EndPoint that represents the remote host. 缓冲区偏移量的默认值为 0。The buffer offset defaults to 0. 大小默认值的长度buffer参数和socketFlags默认值为NoneThe size defaults to the length of the buffer parameter and the socketFlags value defaults to None.

备注

然后再调用ReceiveFrom,则必须显式将绑定Socket到本地终结点使用Bind方法。Before calling ReceiveFrom, you must explicitly bind the Socket to a local endpoint using the Bind method. 如果不,这样做ReceiveFrom将引发SocketExceptionIf you do not, ReceiveFrom will throw a SocketException.

使用无连接协议时,ReceiveFrom将读取第一个排队数据报接收到的本地网络缓冲区。With connectionless protocols, ReceiveFrom will read the first enqueued datagram received into the local network buffer. 如果你收到的数据报大于的大小buffer,则ReceiveFrom方法将填充buffer太多的是,且引发的消息与SocketExceptionIf the datagram you receive is larger than the size of buffer, the ReceiveFrom method will fill buffer with as much of the message as is possible, and throw a SocketException. 如果使用的不可靠的协议,则多余的数据将丢失。If you are using an unreliable protocol, the excess data will be lost. 如果您使用的是可靠的协议,多余的数据将保留由服务提供商可以通过调用检索它ReceiveFrom方法使用一个足够大的缓冲区。If you are using a reliable protocol, the excess data will be retained by the service provider and you can retrieve it by calling the ReceiveFrom method with a large enough buffer.

如果没有任何数据可供读取,ReceiveFrom方法将阻塞,直到有可用数据。If no data is available for reading, the ReceiveFrom method will block until data is available. 如果您是在非阻止模式下,并且没有在可用的数据中的协议堆栈缓冲区ReceiveFrom方法将立即完成并引发SocketExceptionIf you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the ReceiveFrom method will complete immediately and throw a SocketException. 可以使用Available属性来确定数据是否可供读取。You can use the Available property to determine if data is available for reading. Available为非零,重试该接收操作。When Available is non-zero, retry the receive operation.

尽管ReceiveFrom适用于无连接协议,你可以使用面向连接的协议也。Although ReceiveFrom is intended for connectionless protocols, you can use a connection-oriented protocol as well. 如果你选择这样做,则必须首先可以建立远程主机连接通过调用Connect方法,或接受传入的远程主机连接,通过调用Accept方法。If you choose to do so, you must first either establish a remote host connection by calling the Connect method or accept an incoming remote host connection by calling the Accept method. 如果没有建立或接受连接,然后调用ReceiveFrom方法时,将获取SocketExceptionIf you do not establish or accept a connection before calling the ReceiveFrom method, you will get a SocketException. 您还可以建立默认远程主机之前调用的无连接协议ReceiveFrom方法。You can also establish a default remote host for a connectionless protocol prior to calling the ReceiveFrom method. 在这些情况下,任一ReceiveFrom方法将忽略remoteEP参数和仅接收来自连接的数据或默认远程主机。In either of these cases, the ReceiveFrom method will ignore the remoteEP parameter and only receive data from the connected or default remote host.

使用面向连接的套接字ReceiveFrom将读取的数据,可最大的大小bufferWith connection-oriented sockets, ReceiveFrom will read as much data as is available up to the size of buffer. 如果远程主机关闭Socket与连接Shutdown收到了方法,并且所有可用数据,ReceiveFrom方法将立即完成并返回零字节。If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the ReceiveFrom method will complete immediately and return zero bytes.

备注

如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

AddressFamilyEndPoint中使用ReceiveFrom必须与匹配AddressFamilyEndPoint中使用SendToThe AddressFamily of the EndPoint used in ReceiveFrom needs to match the AddressFamily of the EndPoint used in SendTo.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

安全性

SocketPermission
用于接受来自网络的连接。for accepting connections from the network. 关联枚举:AcceptAssociated enumeration: Accept.

另请参阅

ReceiveFrom(Byte[], Int32, SocketFlags, EndPoint) ReceiveFrom(Byte[], Int32, SocketFlags, EndPoint) ReceiveFrom(Byte[], Int32, SocketFlags, EndPoint)

使用指定的 SocketFlags 将指定的字节数接收到数据缓冲区并存储终结点。Receives the specified number of bytes into the data buffer, using the specified SocketFlags, and stores the endpoint.

public:
 int ReceiveFrom(cli::array <System::Byte> ^ buffer, int size, System::Net::Sockets::SocketFlags socketFlags, System::Net::EndPoint ^ % remoteEP);
public int ReceiveFrom (byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP);
member this.ReceiveFrom : byte[] * int * System.Net.Sockets.SocketFlags *  -> int

参数

buffer
Byte[]

类型 Byte 的数组,它是所接受的数据的存储位置。An array of type Byte that is the storage location for received data.

size
Int32 Int32 Int32 Int32

要接收的字节数。The number of bytes to receive.

socketFlags
SocketFlags SocketFlags SocketFlags SocketFlags

SocketFlags 值的按位组合。A bitwise combination of the SocketFlags values.

remoteEP
EndPoint EndPoint EndPoint EndPoint

通过引用传递的 EndPoint,表示远程服务器。An EndPoint, passed by reference, that represents the remote server.

返回

收到的字节数。The number of bytes received.

异常

buffernullbuffer is null.

- 或 --or- remoteEPnullremoteEP is null.

size 小于 0。size is less than 0.

- 或 --or- size 大于 buffer 的长度。size is greater than the length of buffer.

socketFlags 不是有效的值组合。socketFlags is not a valid combination of values.

- 或 --or- 未设置 LocalEndPoint 属性。The LocalEndPoint property was not set.

- 或 --or- 访问 Socket 时出现操作系统错误。An operating system error occurs while accessing the Socket.

调用堆栈中的调用方没有所需的权限。A caller in the call stack does not have the required permissions.

示例

下面的代码示例从远程主机接收无连接的数据报。The following code example receives a connectionless datagram from a remote host. 缓冲区大小,并SocketFlags传递给ReceiveFrom方法。The buffer size, and SocketFlags are passed to the ReceiveFrom method.

static void ReceiveFrom3()
{
   IPHostEntry^ hostEntry = Dns::Resolve( Dns::GetHostName() );
   IPEndPoint^ endPoint = gcnew IPEndPoint( hostEntry->AddressList[ 0 ],11000 );

   Socket^ s = gcnew Socket( endPoint->Address->AddressFamily,
      SocketType::Dgram,
      ProtocolType::Udp );
   
   // Creates an IPEndPoint to capture the identity of the sending host.
   IPEndPoint^ sender = gcnew IPEndPoint( IPAddress::Any,0 );
   EndPoint^ senderRemote = safe_cast<EndPoint^>(sender);
   
   // Binding is required with ReceiveFrom calls.
   s->Bind( endPoint );

   array<Byte>^ msg = gcnew array<Byte>(256);
   Console::WriteLine(  "SWaiting to receive datagrams from client..." );
   // This call blocks. 
   s->ReceiveFrom( msg, msg->Length, SocketFlags::None, senderRemote );
   s->Close();
}
public static void ReceiveFrom3()
{
    IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
    IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);

    Socket s = new Socket(endPoint.Address.AddressFamily,
        SocketType.Dgram,
        ProtocolType.Udp);
  
    // Creates an IPEndPoint to capture the identity of the sending host.
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint senderRemote = (EndPoint)sender;
    
    // Binding is required with ReceiveFrom calls.
    s.Bind(endPoint);
    
    byte[] msg = new Byte[256];
    Console.WriteLine ("Waiting to receive datagrams from client...");
    // This call blocks. 
    s.ReceiveFrom(msg, msg.Length, SocketFlags.None, ref senderRemote);
    s.Close();
}
Public Shared Sub ReceiveFrom3() 
    Dim hostEntry As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
    Dim endPoint As New IPEndPoint(hostEntry.AddressList(0), 11000)
    
    Dim s As New Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
    
    ' Creates an IPEndPoint to capture the identity of the sending host.
    Dim sender As New IPEndPoint(IPAddress.Any, 0)
    Dim senderRemote As EndPoint = CType(sender, EndPoint)
    
    ' Binding is required with ReceiveFrom calls.
    s.Bind(endPoint)
    
    Dim msg() As Byte = New [Byte](255) {}
    Console.WriteLine("Waiting to receive datagrams from client...")
    ' This call blocks. 
    s.ReceiveFrom(msg, msg.Length, SocketFlags.None, senderRemote)
    s.Close()

End Sub 'ReceiveFrom3

注解

ReceiveFrom方法将数据读入buffer参数,返回已成功读取的字节数和捕获从其发送数据的远程主机终结点。The ReceiveFrom method reads data into the buffer parameter, returns the number of bytes successfully read, and captures the remote host endpoint from which the data was sent. 此方法很有用,如果你想要从未知的主机或多个主机接收无连接的数据报。This method is useful if you intend to receive connectionless datagrams from an unknown host or multiple hosts.

此重载仅要求您提供接收缓冲区中,你想要接收所需的字节数SocketFlags,和一个EndPoint表示远程主机。This overload only requires you to provide a receive buffer, the number of bytes you want to receive, the necessary SocketFlags, and an EndPoint that represents the remote host. 缓冲区偏移量的默认值为 0。The buffer offset defaults to 0.

使用无连接协议时,ReceiveFrom将读取第一个排队数据报接收到的本地网络缓冲区。With connectionless protocols, ReceiveFrom will read the first enqueued datagram received into the local network buffer. 如果你收到的数据报大于的大小buffer,则ReceiveFrom方法将填充buffer太多的是,且引发的消息与SocketExceptionIf the datagram you receive is larger than the size of buffer, the ReceiveFrom method will fill buffer with as much of the message as is possible, and throw a SocketException. 如果使用的不可靠的协议,则多余的数据将丢失。If you are using an unreliable protocol, the excess data will be lost. 如果您使用的是可靠的协议,多余的数据将保留由服务提供商可以通过调用检索它ReceiveFrom方法使用一个足够大的缓冲区。If you are using a reliable protocol, the excess data will be retained by the service provider and you can retrieve it by calling the ReceiveFrom method with a large enough buffer.

如果没有任何数据可供读取,ReceiveFrom方法将阻塞,直到有可用数据。If no data is available for reading, the ReceiveFrom method will block until data is available. 如果您是在非阻止模式下,并且没有在可用的数据中的协议堆栈缓冲区ReceiveFrom方法将立即完成并引发SocketExceptionIf you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the ReceiveFrom method will complete immediately and throw a SocketException. 可以使用Available属性来确定数据是否可供读取。You can use the Available property to determine if data is available for reading. Available为非零,重试该接收操作。When Available is non-zero, retry the receive operation.

尽管ReceiveFrom适用于无连接协议,你可以使用面向连接的协议也。Although ReceiveFrom is intended for connectionless protocols, you can use a connection-oriented protocol as well. 如果你选择这样做,则必须首先可以建立远程主机连接通过调用Connect方法,或接受传入的远程主机连接,通过调用Accept方法。If you choose to do so, you must first either establish a remote host connection by calling the Connect method or accept an incoming remote host connection by calling the Accept method. 如果没有建立或接受连接,然后调用ReceiveFrom方法时,将获取SocketExceptionIf you do not establish or accept a connection before calling the ReceiveFrom method, you will get a SocketException. 您还可以建立默认远程主机之前调用的无连接协议ReceiveFrom方法。You can also establish a default remote host for a connectionless protocol prior to calling the ReceiveFrom method. 在这些情况下,任一ReceiveFrom方法将忽略remoteEP参数和仅接收来自连接的数据或默认远程主机。In either of these cases, the ReceiveFrom method will ignore the remoteEP parameter and only receive data from the connected or default remote host.

使用面向连接的套接字ReceiveFrom将读取的数据,可最多指定的字节数size参数。With connection-oriented sockets, ReceiveFrom will read as much data as is available up to the number of bytes specified by the size parameter. 如果远程主机关闭Socket与连接Shutdown收到了方法,并且所有可用数据,ReceiveFrom方法将立即完成并返回零字节。If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the ReceiveFrom method will complete immediately and return zero bytes.

备注

然后再调用ReceiveFrom,则必须显式将绑定Socket到本地终结点使用Bind方法。Before calling ReceiveFrom, you must explicitly bind the Socket to a local endpoint using the Bind method. 如果不,这样做ReceiveFrom将引发SocketExceptionIf you do not, ReceiveFrom will throw a SocketException. 如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

AddressFamilyEndPoint中使用ReceiveFrom必须与匹配AddressFamilyEndPoint中使用SendToThe AddressFamily of the EndPoint used in ReceiveFrom needs to match the AddressFamily of the EndPoint used in SendTo.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

安全性

SocketPermission
用于接受来自网络的连接。for accepting connections from the network. 关联枚举:AcceptAssociated enumeration: Accept.

另请参阅

ReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint) ReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint) ReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint)

使用指定的 SocketFlags 将指定的数据字节数接收到数据缓冲区的指定位置,并存储终结点。Receives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint.

public:
 int ReceiveFrom(cli::array <System::Byte> ^ buffer, int offset, int size, System::Net::Sockets::SocketFlags socketFlags, System::Net::EndPoint ^ % remoteEP);
public int ReceiveFrom (byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP);
member this.ReceiveFrom : byte[] * int * int * System.Net.Sockets.SocketFlags *  -> int

参数

buffer
Byte[]

类型 Byte 的数组,它是所接受的数据的存储位置。An array of type Byte that is the storage location for received data.

offset
Int32 Int32 Int32 Int32

buffer 参数中的位置,用于存储所接收的数据。The position in the buffer parameter to store the received data.

size
Int32 Int32 Int32 Int32

要接收的字节数。The number of bytes to receive.

socketFlags
SocketFlags SocketFlags SocketFlags SocketFlags

SocketFlags 值的按位组合。A bitwise combination of the SocketFlags values.

remoteEP
EndPoint EndPoint EndPoint EndPoint

通过引用传递的 EndPoint,表示远程服务器。An EndPoint, passed by reference, that represents the remote server.

返回

收到的字节数。The number of bytes received.

异常

buffernullbuffer is null.

- 或 --or- remoteEPnullremoteEP is null.

offset 小于 0。offset is less than 0.

- 或 --or- offset 大于 buffer 的长度。offset is greater than the length of buffer.

- 或 --or- size 小于 0。size is less than 0.

- 或 --or- size 大于 buffer 的长度减去偏移量参数的值。size is greater than the length of the buffer minus the value of the offset parameter.

socketFlags 不是有效的值组合。socketFlags is not a valid combination of values.

- 或 --or- 未设置 LocalEndPoint 属性。The LocalEndPoint property was not set.

- 或 --or- 尝试访问套接字时出错。An error occurred when attempting to access the socket.

示例

下面的代码示例从远程主机接收无连接的数据报。The following code example receives a connectionless datagram from a remote host. 偏移量、 缓冲区大小,并SocketFlags传递给ReceiveFrom方法。The offset, buffer size, and SocketFlags are passed to the ReceiveFrom method.

static void ReceiveFrom4()
{
   IPHostEntry^ hostEntry = Dns::Resolve( Dns::GetHostName() );
   IPEndPoint^ endPoint = gcnew IPEndPoint( hostEntry->AddressList[ 0 ],11000 );

   Socket^ s = gcnew Socket( endPoint->Address->AddressFamily,
      SocketType::Dgram,
      ProtocolType::Udp );
   
   // Creates an IpEndPoint to capture the identity of the sending host.
   IPEndPoint^ sender = gcnew IPEndPoint( IPAddress::Any,0 );
   EndPoint^ senderRemote = safe_cast<EndPoint^>(sender);
   
   // Binding is required with ReceiveFrom calls.
   s->Bind( endPoint );

   array<Byte>^ msg = gcnew array<Byte>(256);
   Console::WriteLine(  "SWaiting to receive datagrams from client..." );
   // This call blocks.  
   s->ReceiveFrom( msg, 0, msg->Length, SocketFlags::None, senderRemote );
   s->Close();
}
public static void ReceiveFrom4()
{
    IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
    IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);

    Socket s = new Socket(endPoint.Address.AddressFamily,
        SocketType.Dgram,
        ProtocolType.Udp);
        
    // Creates an IpEndPoint to capture the identity of the sending host.
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint senderRemote = (EndPoint)sender;
    
    // Binding is required with ReceiveFrom calls.
    s.Bind(endPoint);
    byte[] msg = new Byte[256];
    Console.WriteLine ("Waiting to receive datagrams from client...");
    // This call blocks.  
    s.ReceiveFrom(msg, 0, msg.Length, SocketFlags.None, ref senderRemote);
    s.Close();
}
Public Shared Sub ReceiveFrom4() 
    Dim hostEntry As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
    Dim endPoint As New IPEndPoint(hostEntry.AddressList(0), 11000)
    
    Dim s As New Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
    
    ' Creates an IpEndPoint to capture the identity of the sending host.
    Dim sender As New IPEndPoint(IPAddress.Any, 0)
    Dim senderRemote As EndPoint = CType(sender, EndPoint)
    
    ' Binding is required with ReceiveFrom calls.
    s.Bind(endPoint)
    Dim msg() As Byte = New [Byte](255) {}
    Console.WriteLine("Waiting to receive datagrams from client...")
    ' This call blocks.  
    s.ReceiveFrom(msg, 0, msg.Length, SocketFlags.None, senderRemote)
    s.Close()

End Sub 'ReceiveFrom4

注解

ReceiveFrom方法将数据读入buffer参数,返回已成功读取的字节数和捕获从其发送数据的远程主机终结点。The ReceiveFrom method reads data into the buffer parameter, returns the number of bytes successfully read, and captures the remote host endpoint from which the data was sent. 此方法很有用,如果你想要从未知的主机或多个主机接收无连接的数据报。This method is useful if you intend to receive connectionless datagrams from an unknown host or multiple hosts.

使用无连接协议时,ReceiveFrom将读取第一个排队数据报接收到的本地网络缓冲区。With connectionless protocols, ReceiveFrom will read the first enqueued datagram received into the local network buffer. 如果你收到的数据报大于的大小buffer,则ReceiveFrom方法将填充buffer太多的是,且引发的消息与SocketExceptionIf the datagram you receive is larger than the size of buffer, the ReceiveFrom method will fill buffer with as much of the message as is possible, and throw a SocketException. 如果使用的不可靠的协议,则多余的数据将丢失。If you are using an unreliable protocol, the excess data will be lost. 如果您使用的是可靠的协议,多余的数据将保留由服务提供商可以通过调用检索它ReceiveFrom方法使用一个足够大的缓冲区。If you are using a reliable protocol, the excess data will be retained by the service provider and you can retrieve it by calling the ReceiveFrom method with a large enough buffer.

如果没有任何数据可供读取,ReceiveFrom方法将阻塞,直到有可用数据。If no data is available for reading, the ReceiveFrom method will block until data is available. 如果您是在非阻止模式下,并且没有在可用的数据中的协议堆栈缓冲区ReceiveFrom方法将立即完成并引发SocketExceptionIf you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the ReceiveFrom method will complete immediately and throw a SocketException. 可以使用Available属性来确定数据是否可供读取。You can use the Available property to determine if data is available for reading. Available为非零,重试该接收操作。When Available is non-zero, retry the receive operation.

尽管ReceiveFrom适用于无连接协议,你可以使用面向连接的协议也。Although ReceiveFrom is intended for connectionless protocols, you can use a connection-oriented protocol as well. 如果你选择这样做,则必须首先可以建立远程主机连接通过调用Connect方法,或接受传入的远程主机连接,通过调用Accept方法。If you choose to do so, you must first either establish a remote host connection by calling the Connect method or accept an incoming remote host connection by calling the Accept method. 如果没有建立或接受连接,然后调用ReceiveFrom方法时,将获取SocketExceptionIf you do not establish or accept a connection before calling the ReceiveFrom method, you will get a SocketException. 您还可以建立默认远程主机之前调用的无连接协议ReceiveFrom方法。You can also establish a default remote host for a connectionless protocol prior to calling the ReceiveFrom method. 在这些情况下,任一ReceiveFrom方法将忽略remoteEP参数和仅接收来自连接的数据或默认远程主机。In either of these cases, the ReceiveFrom method will ignore the remoteEP parameter and only receive data from the connected or default remote host.

使用面向连接的套接字ReceiveFrom将读取的数据,可最多指定的字节量size参数。With connection-oriented sockets, ReceiveFrom will read as much data as is available up to the amount of bytes specified by the size parameter. 如果远程主机关闭Socket与连接Shutdown收到了方法,并且所有可用数据,ReceiveFrom方法将立即完成并返回零字节。If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been Received, the ReceiveFrom method will complete immediately and return zero bytes.

备注

然后再调用ReceiveFrom,则必须显式将绑定Socket到本地终结点使用Bind方法。Before calling ReceiveFrom, you must explicitly bind the Socket to a local endpoint using the Bind method. 如果不,这样做ReceiveFrom将引发SocketExceptionIf you do not, ReceiveFrom will throw a SocketException. 如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

AddressFamilyEndPoint中使用ReceiveFrom必须与匹配AddressFamilyEndPoint中使用SendToThe AddressFamily of the EndPoint used in ReceiveFrom needs to match the AddressFamily of the EndPoint used in SendTo.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

安全性

SocketPermission
用于接受来自网络的连接。for accepting connections from the network. 关联枚举:AcceptAssociated enumeration: Accept.

另请参阅

适用于