I would like to send a message directly after a device has connected to me.
So I start listening to incoming connections:
public static void StartListen(BluetoothDeviceInfo foundDevice)
{
try
{
_listener = new BluetoothListener(_serviceClass);
_listener.Start();
_listener.BeginAcceptBluetoothClient(AcceptBluetoothClientCallback, _listener);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
Then I accept the the connection in an async way:
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();
}
But AcceptBluetoothClient
is a blocking call. So I don't get the client until the other part sends something. Is there a way to get the client/stream before this event?
From what I see in the code, you are calling AcceptBluetoothClient twice, one of the calls is Asynchronous, and the other is Synchronous (blocking). You mentioned that you are accepting the connection in an async way (and that's by calling BeginAcceptBluetoothClient), so you do not need to call AcceptBluetoothClient again inside the callback function AcceptBluetoothClientCallback, because at that moment you already accepted the new client. So, you just need to get the stream and continue the flow.