Created
November 3, 2017 09:58
-
-
Save claudiohilario/4c25e2780735202f8cd26eff8a51b0eb to your computer and use it in GitHub Desktop.
UDP Datagramsockets WinRT (Funcional)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using Windows.Networking.Sockets; | |
using Windows.Networking; | |
using Windows.Storage; | |
using System; | |
using Windows.Foundation; | |
using System.Runtime.InteropServices.WindowsRuntime; | |
using System.Threading.Tasks; | |
using System.Net.Sockets; | |
using System.Net; | |
using Windows.Web.Http; | |
using System.Threading; | |
using Windows.Storage.Streams; | |
using System.Text; | |
namespace UdpDataResponse | |
{ | |
public sealed class UdpDataResponse | |
{ | |
public static IAsyncOperation<string> getudpdata(string pedido) | |
{ | |
var task = Task.Run(async () => | |
{ | |
string response = "SEM RESPOSTA"; | |
DatagramSocket socket = new DatagramSocket(); | |
TypedEventHandler<DatagramSocket, DatagramSocketMessageReceivedEventArgs> handler = (sender, args) => | |
{ | |
Stream streamIn = args.GetDataStream().AsStreamForRead(); | |
StreamReader reader = new StreamReader(streamIn); | |
//Read the message that was received from the UDP echo server. | |
response = reader.ReadLineAsync().Result; | |
reader.Dispose(); | |
}; | |
socket.MessageReceived += handler; | |
string serverPort = "xxxx"; | |
//Bind the socket to the clientPort so that we can start listening for UDP messages from the UDP echo server. | |
try | |
{ | |
using (var stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), serverPort)) | |
{ | |
using (var writer = new DataWriter(stream)) | |
{ | |
var data = Encoding.UTF8.GetBytes(pedido); | |
writer.WriteBytes(data); | |
writer.StoreAsync(); | |
} | |
} | |
} | |
catch (Exception e) | |
{ | |
response = "PORTA OCUPADA"; | |
} | |
await Task.Delay(1000); | |
socket.Dispose(); | |
return response; | |
}); | |
return task.AsAsyncOperation(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment