我在 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()
{
}
}