32feet AcceptBluetoothClient 后直接发送消息
Send message directly after AcceptBluetoothClient with 32feet
我想在设备连接到我后直接发送消息。
所以我开始监听传入的连接:
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
是一个阻塞调用。因此,在另一部分发送内容之前,我不会得到客户。有没有办法在这个事件之前得到 client/stream?
根据我在代码中看到的情况,您调用了两次 AcceptBluetoothClient,其中一次是异步调用,另一次是同步调用(阻塞)。
您提到您正在以异步方式接受连接(这是通过调用 BeginAcceptBluetoothClient),因此您不需要在内部再次调用 AcceptBluetoothClient回调函数 AcceptBluetoothClientCallback,因为此时您已经接受了新客户端。所以,你只需要获取流并继续流。
我想在设备连接到我后直接发送消息。
所以我开始监听传入的连接:
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
是一个阻塞调用。因此,在另一部分发送内容之前,我不会得到客户。有没有办法在这个事件之前得到 client/stream?
根据我在代码中看到的情况,您调用了两次 AcceptBluetoothClient,其中一次是异步调用,另一次是同步调用(阻塞)。 您提到您正在以异步方式接受连接(这是通过调用 BeginAcceptBluetoothClient),因此您不需要在内部再次调用 AcceptBluetoothClient回调函数 AcceptBluetoothClientCallback,因为此时您已经接受了新客户端。所以,你只需要获取流并继续流。