Async Methods - return string from UDP

5

I'm developing a code whose purpose is to send a packet with a broadcast string and then read the response (if any), however I want to create a method that just returns the response string. I have the following, based on the example provided by windows:

private async void testUdpSocketServer(string message) {

  DatagramSocket socket = new DatagramSocket();
  socket.MessageReceived += Socket_MessageReceived;

  //You can use any port that is not currently in use already on the machine. We will be using two separate and random 
  //ports for the client and server because both the will be running on the same machine.
  string serverPort = "1337";
  string clientPort = "1338";

  //Because we will be running the client and server on the same machine, we will use localhost as the hostname.
  Windows.Networking.HostName serverHost = new Windows.Networking.HostName("255.255.255.255");

  //Bind the socket to the clientPort so that we can start listening for UDP messages from the UDP echo server.
  await socket.BindServiceNameAsync(clientPort);

  //Write a message to the UDP echo server.
  Stream streamOut = (await socket.GetOutputStreamAsync(serverHost, serverPort)).AsStreamForWrite();
  StreamWriter writer = new StreamWriter(streamOut);

  await writer.WriteLineAsync(message);
  await writer.FlushAsync();
}

private async void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) {
  //Read the message that was received from the UDP echo server.
  Stream streamIn = args.GetDataStream().AsStreamForRead();
  StreamReader reader = new StreamReader(streamIn);
  string message = await reader.ReadLineAsync();
}

Now I wanted to develop a method like this to return the string using the testUdpSocketServer(string message) method call, how can I do that?

    
asked by anonymous 17.10.2017 / 17:05

1 answer

1

If I understand you, you want to create a method that calls asynchronously to the testUdpSocketServer method. This can be done in two ways:

  • Add a return of type "System.Threading.Tasks. Task " in your function so it can be ' awaitable ': / p>

    private async Task testUdpSocketServer(string message) { // código... } So you could call the test using: await testUdpSocketServer(msg);

  • Use a Task to do the job:

    Task.Run(async ()=> { await testUdpSocketServer(msg); });

10.11.2017 / 01:35