![](/img/trans.png)
[英]Using incoming data from bluetooth connection for specific objects? C# Windows Form App & Java Android App
[英]bluetooth communication between android app and c# windows form app
我在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()
{
}
}
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,以便它不會假定它已經啟動了服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.