Simple C# Windows Bluetooth Chat Application Part 1 – Server Side

Simple C# Windows Bluetooth Chatting Application

Using 32Feet.NET library

Part 1 – Server Side

Hey guys! Today I’m
going to teach you how to build a simple Bluetooth application. The application
we are going to make is a simple one. This is the scenario, there are two kind applications,
one is the server which is accepting connection from client, and the other is the
client which is attempting connection to server. After the connection
established, they (both client and server) can communicate or chat.

Before we begin, we have to
prepare what we need. These are the requirements:

OS: Windows XP, Windows 7 (recommended)

Software:  Visual Studio C# 2008
Express, VSTS 2010 (recommended)

Library: 32Feet.NET library, you can
download here.

Hardware:  Bluetooth adapter device (use
the adapter that already supports plug and play in windows. I use this, epro
TINY Bluetooth Dongle)

As I’ve told you before,
there are 2 applications we are going to build the client and the server. So, I
will build those two in 2 different computers. The server will be built in XP
and the client will be built in win 7. Both of them must have Bluetooth adapter
device.

Now we begin to build.

Preparing the project

I assumed you already have the library,
Bluetooth adapter, and the IDE, Visual Studio.


Open your visual studio and create
new C# windows form application. In the solution explorer, right click “References”
and click “add reference”. Choose tab “Browse” and find where the library are.

bluetooth01


To check whether the library
referenced correctly, go to code view (*.cs) and try to reference the library
(with “using” keyword).

Then try simple code
like this.

Those codes are to
show a dialog to let user choose all discovered Bluetooth dialog when the
computer has Bluetooth supported. This is the screen shot of the code result in
both xp and windows 7.

The Server Side

The server that we are going to build is
very simple. It just waiting incoming connection and accept it. After the
connection established, it can send and receive messages. This is the design of
its form:

Now we’re heading to code part. This is
the whole code of server application and the explanation of every section of

//just importing the library

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Threading;

using System.Net.Sockets;

//importing InTheHand library

using InTheHand.Net.Bluetooth;

using InTheHand.Windows.Forms;

using InTheHand.Net.Sockets;

using InTheHand.Net.Bluetooth.AttributeIds;

namespace TesBluetoothLagi

{

public partial class Form1 : Form

{

// Threads

Thread AcceptAndListeningThread;

// helper variable

Boolean isConnected = false;

//bluetooth stuff

BluetoothClient btClient;  //represent the bluetooth client
connection

BluetoothListener btListener; //represent this server bluetooth
device

public Form1()

{

InitializeComponent();

//when the bluetooth is supported by this computer

if (BluetoothRadio.IsSupported)

{

UpdateLogText(“Bluetooth Supported!”);

UpdateLogText(“—————————–“);

//getting device information

UpdateLogText(“Primary Bluetooth Radio Name :
” + BluetoothRadio.PrimaryRadio.Name);

UpdateLogText(“Primary Bluetooth Radio Address :
” + BluetoothRadio.PrimaryRadio.LocalAddress);

UpdateLogText(“Primary Bluetooth Radio
Manufacturer : ” + BluetoothRadio.PrimaryRadio.Manufacturer);

UpdateLogText(“Primary Bluetooth Radio Mode :
” + BluetoothRadio.PrimaryRadio.Mode);

UpdateLogText(“Primary Bluetooth Radio Software
Manufacturer : ” + BluetoothRadio.PrimaryRadio.SoftwareManufacturer);

UpdateLogText(“—————————–“);

//creating and starting the thread

AcceptAndListeningThread = new Thread(AcceptAndListen);

AcceptAndListeningThread.Start();

}

else

{

UpdateLogText(“Bluetooth not Supported!”);

}

}

//the function of the thread

public void AcceptAndListen()

{

while (true) {

if (isConnected)

{

//TODO: if there is a device connected

//listening

try

{

UpdateLogTextFromThread(“Listening….”);

NetworkStream stream = btClient.GetStream();

Byte[] bytes = new Byte[512];

String retrievedMsg = “”;

stream.Read(bytes, 0, 512);

stream.Flush();

for (int i = 0; i < bytes.Length; i++)

{

retrievedMsg += Convert.ToChar(bytes[i]);

}

UpdateLogTextFromThread(btClient.RemoteMachineName + ” : ” + retrievedMsg);

UpdateLogTextFromThread(“”);

if (!retrievedMsg.Contains(“server
check”))

{

sendMessage(“Message Received!”);

}

}

catch (Exception ex)

{

UpdateLogTextFromThread(“There is an error
while listening connection”);

UpdateLogTextFromThread(ex.Message);

isConnected = btClient.Connected;

}

}

else

{

//TODO: if there is no connection

// accepting

try

{

btListener = new
BluetoothListener(BluetoothService.TcpProtocol);

UpdateLogTextFromThread(“Listener created
with TCP Protocol service ” + BluetoothService.TcpProtocol);

UpdateLogTextFromThread(“Starting
Listener….”);

btListener.Start();

UpdateLogTextFromThread(“Listener
Started!”);

UpdateLogTextFromThread(“Accepting
incoming connection….”);

btClient = btListener.AcceptBluetoothClient();

isConnected = btClient.Connected;

UpdateLogTextFromThread(“A Bluetooth
Device Connected!”);

}

catch (Exception e)

{

UpdateLogTextFromThread(“There is an error
while accepting connection”);

UpdateLogTextFromThread(e.Message);

UpdateLogTextFromThread(“Retrying….”);

}

}

}

}

//this section is to create a method that allow thread
accessing form’s component

//we can’t update the text of the textbox directly from thread,
so, we use this delegate function

delegate void UpdateLogTextFromThreadDelegate(String msg);

public void UpdateLogTextFromThread(String msg)

{

if (!this.IsDisposed && logsText.InvokeRequired) {

logsText.Invoke(new
UpdateLogTextFromThreadDelegate(UpdateLogText), new Object[]{msg});

}

}

//just ordinary function to update the log text.

//after updating, we move the cursor to the end of text and
scroll it to the cursor.

public void UpdateLogText(String msg)

{

logsText.Text += msg + Environment.NewLine;

logsText.SelectionStart = logsText.Text.Length;

logsText.ScrollToCaret();

}

//function to send message to the client

public Boolean sendMessage(String msg) {

try

{

if (!msg.Equals(“”))

{

UTF8Encoding encoder = new UTF8Encoding();

NetworkStream stream = btClient.GetStream();

stream.Write(encoder.GetBytes(msg + “\n”),
0, encoder.GetBytes(msg).Length);

stream.Flush();

}

}

catch (Exception ex)

{

UpdateLogTextFromThread(“There is an error while
sending message”);

UpdateLogTextFromThread(ex.Message);

try

{

isConnected = btClient.Connected;

btClient.GetStream().Close();

btClient.Dispose();

btListener.Server.Dispose();

btListener.Stop();

}

catch (Exception)

{

}

return false;

}

return true;

}

//when closing or exiting application, we have to close connection and
aborting the thread.

//Otherwise, the process of the thread still running in the background.

private void Form1_FormClosing(object sender,
FormClosingEventArgs e)

{

try

{

AcceptAndListeningThread.Abort();

btClient.GetStream().Close();

btClient.Dispose();

btListener.Stop();

}

catch (Exception)

{

}

}

private void sendBtn_Click(object sender, EventArgs e)

{

sendMessage(messageText.Text);

}

}

}

Note :

To check whether the connection still connected or not, we can use
BluetoothClient.Connected to get the information. However, the condition of
connection contains only the most recent condition, not all time. So, We have
to send a message through the connection to find out the last condition. If it
fail to send message, then connection is no longer available.

End of section. We have finished the server side. Now we can advance to
the client side. You can get the server solution here : TesBluetoothLagi-server

About thejackal

7th semester undergraduate binus university in 2010.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *