我在Android应用和C#Windows窗体应用之间使用蓝牙通信。 Android应用程序用作客户端,C#应用程序用作服务器。我只能处理服务器(笔记本电脑)上的连接,当我断开连接并再次尝试连接时似乎没有发生任何事情。我认为客户端工作正常,因为我已经用另一个移动设备测试了它,而且这个错误在服务器代码中。
这是服务器代码:
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()
{
}
}
答案 0 :(得分:0)
catch(IOException除外) {
updateui("client has been disconnected\n");
connectserver.Abort();
severstart = false; // add this line to the catch block.
client.Close();
mstream.Flush();
break;
}
将severstart设置为false,以便它不会假设它已经启动了服务器。