Search code examples
c#socketsasyncsocketupnp

Why is the async socket send.completed event not fired?


Trying to sent out out a uPNP discovery request. Hoping the issue is something simple. Is there a reason why SendEvent_Completed is not fired?

public void Send() {
  var request = $"M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\nST: ssdp:all\r\n";
  var requestData = Encoding.UTF8.GetBytes(request);

  var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  socket.SendBufferSize = requestData.Length;

  var sendEvent = new SocketAsyncEventArgs();
  sendEvent.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);
  sendEvent.SetBuffer(requestData, 0, requestData.Length);
  sendEvent.Completed += SendEvent_Completed; ;

  socket.SendToAsync(sendEvent);
}

private void SendEvent_Completed(object sender, SocketAsyncEventArgs e) {
  Console.WriteLine("SendEvent_Completed"); // never called why?!
}

Solution

  • The obvious reason it would not be raised is if SendToAsync returns false:

    false if the I/O operation completed synchronously. In this case, The Completed event on the e parameter will not be raised and the e object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation.

    Since you're not currently inspecting that value at all, there's no way to know whether the event will be raised in your current code.