Async methods - return string from UDP

Asked

Viewed 124 times

5

I am developing a code whose goal is to send a package with a string in broadcast and then read the answer (if any), however I want to create a method that just returns the string of the answer. 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 intended to develop a method like this to return the string using the method call testUdpSocketServer(string message), how can I do this?

1 answer

1

If I understand correctly, you want to create a method that makes the asynchronous call to the method testUdpSocketServer. This can be accomplished in two ways:

  • Add a return of type "System.Threading.Tasks.Task" in its function so that it can be 'awaitable' :

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

  • Use a Task do the work:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.