在接受蓝牙客户端后直接发送消息 32英尺.



我想在设备连接到我后直接发送消息。

所以我开始监听传入的连接:

public static void StartListen(BluetoothDeviceInfo foundDevice)
{
try
{
_listener = new BluetoothListener(_serviceClass);
_listener.Start();
_listener.BeginAcceptBluetoothClient(AcceptBluetoothClientCallback, _listener);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}

然后我以异步方式接受连接:

private static void AcceptBluetoothClientCallback(IAsyncResult ar)
{
_client = _listener.AcceptBluetoothClient();
var stream = _client.GetStream();

var data = "hello";
stream.Write(Encoding.ASCII.GetBytes(data), 0, data.Length);
Console.WriteLine($"canRead: {stream.CanRead}");
Console.WriteLine($"canWrite: {stream.CanWrite}");
_client.Close();
}

AcceptBluetoothClient是一个阻止电话。所以我不会得到客户端,直到另一部分发送一些东西。有没有办法在此事件之前获取客户端/流?

从我在代码中看到的内容来看,您正在调用AcceptBluetoothClient两次,其中一个调用是异步的,另一个是同步(阻塞(。 您提到您正在以异步方式接受连接(即通过调用 BeginAcceptBluetoothClient(,因此您无需在回调函数AcceptBluetoothClientCallback中再次调用AcceptBluetoothClient,因为那时您已经接受了新客户端。因此,您只需要获取流并继续流。

最新更新