I am using Bluetooth communication between an Android app and a C# Windows form app. The Android app works as a client and the C# app as a server. I can handle only on connection on the server (laptop) and when I disconnect and try to connect again nothing seems to be happening. I think that the client side works properly because I haved tested it with another mobile and the bug is in server code.
This is the server code:
public partial class Form1 : Form
{
Thread connectserver;
Stream mstream;
BluetoothClient client;
BluetoothListener bluelisten;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (serverstart)
{
updateui("server already started");
}
connectasserver();
}
private void connectasserver()
{
connectserver=new Thread(new ThreadStart (serverconnectedthread));
connectserver.Start();
}
Guid muuid = new Guid("00001101-0000-1000-8000-00805F9B34FB");
bool serverstart = false;
public void serverconnectedthread()
{
serverstart = true;
updateui("waiting for connections of clients\n");
bluelisten = new BluetoothListener(muuid);
bluelisten.Start();
client = new BluetoothClient();
client = bluelisten.AcceptBluetoothClient();
updateui("client has connected\n");
mstream=client.GetStream();
while(true)
{
try
{
byte[] recieved = new byte[1024];
mstream.Read(recieved, 0, recieved.Length);
updateui("recieved: " + Encoding.ASCII.GetString(recieved));
byte[] sent = Encoding.ASCII.GetBytes(" hello world\n");
mstream.Write(sent, 0, sent.Length);
}
catch(IOException except)
{
updateui("client has been disconnected\n");
connectserver.Abort();
client.Close();
mstream.Flush();
break;
}
}
}
private void updateui(string mess)
{
Func<int> del = delegate()
{
textbox3.AppendText(mess + System.Environment.NewLine);
return 0;
};
Invoke(del);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox3_TextChanged()
{
}
}