You must have seen apps that search for other devices and connect to them wirelessly . You can do this in your app by using UDP socket .
User Datagram Protocol
The User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite (the set of network protocols used for the Internet). With UDP, applications can send messages, in this case referred to as datagrams , to other hosts on an Internet Protocol (IP) network without prior communications to set up special transmission channels or data paths. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768.
Applications communicates with other applications/devices by sending and receiving data .
To send data over to another application/device/computer add the following code to your project .
parameters : This function takes the IP address of the remote/other device that is running the udp listener . When the remote device receives the datagram(message) it can reply to it and the SocketOnMessageReceived function will be called in our app where we can retrieve the reply send by the device .
User Datagram Protocol
The User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite (the set of network protocols used for the Internet). With UDP, applications can send messages, in this case referred to as datagrams , to other hosts on an Internet Protocol (IP) network without prior communications to set up special transmission channels or data paths. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768.
Applications communicates with other applications/devices by sending and receiving data .
To send data over to another application/device/computer add the following code to your project .
parameters : This function takes the IP address of the remote/other device that is running the udp listener . When the remote device receives the datagram(message) it can reply to it and the SocketOnMessageReceived function will be called in our app where we can retrieve the reply send by the device .
private async Task send(string ip){
var udpsoc = new DatagramSocket();
try {
udpsoc.MessageReceived += SocketOnMessageReceived;
using (var stream = await udpsoc.GetOutputStreamAsync(new HostName(ip), "remoteserviceName")){
using (var writer = new DataWriter(stream))
{
var data = Encoding.UTF8.GetBytes("searchserver,192.168.2.5");
writer.WriteBytes(data);
writer.StoreAsync();
}
}
}
catch(Exception exp){
tb1.Text = exp.ToString();
}
}
private void SocketOnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
var result = args.GetDataStream();
var resultStream = result.AsStreamForRead(1024);
using (var reader = new StreamReader(resultStream))
{
MemoryStream ms = new MemoryStream();
resultStream.CopyTo(ms);
string text = Encoding.UTF8.GetString(ms.ToArray(), 0, ms.ToArray().Length);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
tb1.Text = text;
});
}
}
No comments:
Post a Comment