When I want to received UDP datagrams asynchronously, I write call BeginReceiveFrom of a System.Net.Sockets.Socket class. The BeginReceiveFrom method expects an Endpoint as the remoteEP parameter.
public IAsyncResult BeginReceiveFrom (
byte[] buffer,
int offset,
int size,
SocketFlags socketFlags,
ref EndPoint remoteEP,
AsyncCallback callback,
Object state
)
This Method starts an asynchronous receive and cannot return any result in remoteEP since it returns immediately. Is this parameter for a kind of filtering or will it be modified on receive completion?
In the receive handler I call EndReceiveFrom, where I also have to pass a reference to an Enpoint object as the endPoint parameter.
public int EndReceiveFrom (
IAsyncResult asyncResult,
ref EndPoint endPoint
)
The EndReceive开发者_StackOverflow中文版From indicates with this Endpoint object the sender of the UDP frame. Why must I pass a remoteEP to the BeginReceiveFrom and can I avoid this?
There's no overloads that do not require an endpoint, but that doesn't mean you have to specify specific endpoints. You can specify any ip address as the remoteEP.
EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
EndReceiveFrom expects a pass by ref variable that will be populated by the method call itself. You can instantiate the endPoint similarly.
EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0);
After the call is made, simply ignore the value of receivedFromEP if you do not need it.
精彩评论