Introduction
If you want to know how to use the Bluetooth features to send data using your SmartPhone, you are at the right place. Here, we will learn that together step by step.
Background
Bluetooth is a wireless communication technology that devices use to communicate with each other within just a 10 meter. So we must include ID_CAP_PROXIMITY
and ID_CAP_NETWORKING
capabilities in our application manifest.
Using the Code
First of all, we must discover other devices and applications using the PeerFinder
class.
StreamSocket socket;public async void FindPeers()
{
IReadOnlyList<PeerInformation> peers = await PeerFinder.FindAllPeersAsync();
if (peers.Count > 0)
{ socket = await PeerFinder.ConnectAsync(peers[0]); PeerFinder.Stop();
}
}
Then, the application searches to see if it is running an instance of itself.
public void Advertise()
{
PeerFinder.DisplayName ="SuperMario";
PeerFinder.Start();
}
Now, it is important to use the StreamSocket
instance to connect to the peer application.
public void MySampleApp()
{
PeerFinder.ConnectionRequested += PeerFinder_connexionRequested;
}
private void PeerFinder_connexionRequested
(object sender, ConnectionRequestedEventArgs args)
{
MessageBoxResult result = MessageBox.Show
(string.Format("{0} is trying to connect.
Would you like to accept?",args.PeerInformation.DisplayName),
"My bleutooth Chat App",MessageBoxButton.OKCancel );
if (result == MessageBoxResult.OK)
{
socket.Connect(args.PeerInformation);
}
}
Great! So we want to read the incoming messages that are transmitted from another device or peer applications. That is why we use the DataReader
class to load and read data.
DataReader dataReader = new DataReader(socket.InputStream);
await dataReader.loadAsync(4);uint messageLen =(uint)DataReader.readInt32();
await dataReader.loadAsync(messageLen)String Message = dataReader.ReadString(messageLen);
And we use the DataWriter
class in order to send outgoing messages to an external device or peer application.
DataWriter dataWriter = new DataWriter(socket.OutputStream);
dataWriter.WriteInt32(Message.length);
await dataWriter.StoreAsync();
dataWriter.WriteString(message);
await dataWriter.StoreAsync();
Any comments are most welcome.