从手机到PC的蓝牙连接C#Xamarin.Forms
开发者们好!我目前正在做一个项目,需要一个从手机到电脑的蓝牙连接,传输一些数据并输出到PuTTY上。但问题是,每当我想连接套接字时,它都会给我以下错误: 读取失败,套接字可能已关闭或超时,读取重试:-1从手机到PC的蓝牙连接C#Xamarin.Forms,c#,android,xamarin.forms,bluetooth,C#,Android,Xamarin.forms,Bluetooth,开发者们好!我目前正在做一个项目,需要一个从手机到电脑的蓝牙连接,传输一些数据并输出到PuTTY上。但问题是,每当我想连接套接字时,它都会给我以下错误: 读取失败,套接字可能已关闭或超时,读取重试:-1 使用系统; 使用System.Collections.Generic; 使用系统诊断; 使用System.Linq; 使用系统文本; 使用系统线程; 使用System.Threading.Tasks; 使用Android.App; 使用Android.Bluetooth; 使用Android.C
使用系统;
使用System.Collections.Generic;
使用系统诊断;
使用System.Linq;
使用系统文本;
使用系统线程;
使用System.Threading.Tasks;
使用Android.App;
使用Android.Bluetooth;
使用Android.Content;
使用Android.OS;
使用Android.Runtime;
使用Android.Views;
使用Android.Widget;
使用BluetoothSample.Droid.PlatformSpecifics;
使用BluetoothSample.Services.Interfaces;
使用Java.Util;
使用Xamarin.Forms;
使用Debug=System.Diagnostics.Debug;
[程序集:依赖项(typeof(BluetoothService))]
命名空间BluetoothSample.Droid.PlatformSpecifics
{
公共类蓝牙服务:IBluetoothService
{
私有CancellationTokenSource _cancellationToken{get;}
公共字符串MessageToSend{get;set;}
公共蓝牙服务
{
_cancellationToken=新的CancellationTokenSource();
}
公共void Connect(字符串名称)
{
运行(异步()=>等待连接设备(名称));
}
专用异步任务连接设备(字符串名称)
{
BluetoothDevice=null;
BluetoothAdapter=BluetoothAdapter.DefaultAdapter;
BluetoothSocket bthSocket=null;
while(_cancellationToken.IsCancellationRequested==false)
{
尝试
{
睡眠(250);
适配器=BluetoothAdapter.DefaultAdapter;
if(适配器==null)
Debug.Write(“未找到蓝牙适配器!”);
其他的
编写(“找到适配器!”);
如果(!adapter.IsEnabled)
Debug.Write(“蓝牙适配器未启用”);
其他的
编写(“找到适配器!”);
Debug.Write(“尝试连接到”+name);
foreach(适配器中的var bondedDevice.BondedDevices)
{
Debug.Write(“找到配对设备:”+bondedDevice.Name.ToUpper());
if(bondedDevice.Name.ToUpper().IndexOf(Name.ToUpper())>=0)
{
Debug.Write(“找到”+bondedDevice.Name+”。尝试连接它!);
设备=绑定设备;
打破
}
}
如果(设备==null)
Debug.Write(“未找到命名设备”);
其他的
{
UUID UUID=UUID.FromString(“000011101-0000-1000-8000-00805f9b34fb”);
bthSocket=device.createrFComsockettoServiceRecord(uuid);
如果(bthSocket!=null)
{
adapter.CancelDiscovery();
等待bthSocket.ConnectAsync();
如果(bthSocket.断开连接)
{
调试。写入(“连接”);
while(_cancellationToken.IsCancellationRequested==false)
{
if(MessageToSend!=null)
{
var chars=MessageToSend.ToCharArray();
var bytes=新列表();
foreach(字符中的变量字符)
{
字节。添加((字节)字符);
}
等待bthSocket.OutputStream.WriteAsync(bytes.ToArray(),0,bytes.Count);
MessageToSend=null;
}
}
}
}
}
}
捕获(例外情况除外)
{
Debug.Write(ex);
Debug.Write(例如消息);
}
最后
{
如果(bthSocket!=null)
bthSocket.Close();
设备=空;
适配器=空;
}
}
}
公共空间断开连接()
{
如果(_cancellationToken!=null)
{
_cancellationToken.Cancel();
}
}
公共列表PairedDevices()
{
BluetoothAdapter=BluetoothAdapter.DefaultAdapter;
列表设备=新列表();
foreach(适配器中的var bondedDevices.bondedDevices)
添加(bondedDevices.Name);
返回装置;
}
公共无效发送(字符串消息)
{
if(MessageToSend==null)
MessageToSend=消息;
}
}
}
好的,所以我用以下代码块替换了我的ConnectDevice()
函数,从而解决了我的问题:
private async Task ConnectDevice(string name)
{
BluetoothDevice device = null;
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
BluetoothSocket bthSocket = null;
BluetoothServerSocket bthServerSocket = null;
UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
bthServerSocket = adapter.ListenUsingRfcommWithServiceRecord("TLCI Barcode Scanner", uuid);
_cancellationToken = new CancellationTokenSource();
while (_cancellationToken.IsCancellationRequested == false)
{
try
{
Thread.Sleep(250);
adapter = BluetoothAdapter.DefaultAdapter;
if (adapter == null)
Debug.Write("No bluetooth adapter found!");
else
Debug.Write("Adapter found!");
if (!adapter.IsEnabled)
Debug.Write("Bluetooth adapter is not enabled.");
else
Debug.Write("Adapter found!");
Debug.Write("Try to connect to " + name);
foreach (var bondedDevice in adapter.BondedDevices)
{
Debug.Write("Paired devices found: " + bondedDevice.Name.ToUpper());
if (bondedDevice.Name.ToUpper().IndexOf(name.ToUpper()) >= 0)
{
Debug.Write("Found " + bondedDevice.Name + ". Try to connect with it!");
device = bondedDevice;
Debug.Write(bondedDevice.Type.ToString());
break;
}
}
if (device == null)
Debug.Write("Named device not found.");
else
{
bthSocket = bthServerSocket.Accept();
adapter.CancelDiscovery();
if (bthSocket != null)
{
Debug.Write("Connected");
if (bthSocket.IsConnected)
{
var mReader = new InputStreamReader(bthSocket.InputStream);
var buffer = new BufferedReader(mReader);
while (_cancellationToken.IsCancellationRequested == false)
{
if (MessageToSend != null)
{
var chars = MessageToSend.ToCharArray();
var bytes = new List<byte>();
foreach (var character in chars)
{
bytes.Add((byte)character);
}
await bthSocket.OutputStream.WriteAsync(bytes.ToArray(), 0, bytes.Count);
MessageToSend = null;
}
}
}
}
}
}
catch (Exception ex)
{
Debug.Write(ex);
Debug.Write(ex.Message);
}
finally
{
if (bthSocket != null)
bthSocket.Close();
device = null;
adapter = null;
}
}
}
专用异步任务连接设备(字符串名称)
{
BluetoothDevice=null;
BluetoothAdapter=BluetoothAdapter.DefaultAdapter;
BluetoothSocket bthSocket=null;
BluetoothServerSocket bthServerSocket=null;
UUID UUID=UUID.FromString(“000011101-0000-1000-8000-00805f9b34fb”);
bthServerSocket=adapter.listenusingrfcommiths
private async Task ConnectDevice(string name)
{
BluetoothDevice device = null;
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
BluetoothSocket bthSocket = null;
BluetoothServerSocket bthServerSocket = null;
UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
bthServerSocket = adapter.ListenUsingRfcommWithServiceRecord("TLCI Barcode Scanner", uuid);
_cancellationToken = new CancellationTokenSource();
while (_cancellationToken.IsCancellationRequested == false)
{
try
{
Thread.Sleep(250);
adapter = BluetoothAdapter.DefaultAdapter;
if (adapter == null)
Debug.Write("No bluetooth adapter found!");
else
Debug.Write("Adapter found!");
if (!adapter.IsEnabled)
Debug.Write("Bluetooth adapter is not enabled.");
else
Debug.Write("Adapter found!");
Debug.Write("Try to connect to " + name);
foreach (var bondedDevice in adapter.BondedDevices)
{
Debug.Write("Paired devices found: " + bondedDevice.Name.ToUpper());
if (bondedDevice.Name.ToUpper().IndexOf(name.ToUpper()) >= 0)
{
Debug.Write("Found " + bondedDevice.Name + ". Try to connect with it!");
device = bondedDevice;
Debug.Write(bondedDevice.Type.ToString());
break;
}
}
if (device == null)
Debug.Write("Named device not found.");
else
{
bthSocket = bthServerSocket.Accept();
adapter.CancelDiscovery();
if (bthSocket != null)
{
Debug.Write("Connected");
if (bthSocket.IsConnected)
{
var mReader = new InputStreamReader(bthSocket.InputStream);
var buffer = new BufferedReader(mReader);
while (_cancellationToken.IsCancellationRequested == false)
{
if (MessageToSend != null)
{
var chars = MessageToSend.ToCharArray();
var bytes = new List<byte>();
foreach (var character in chars)
{
bytes.Add((byte)character);
}
await bthSocket.OutputStream.WriteAsync(bytes.ToArray(), 0, bytes.Count);
MessageToSend = null;
}
}
}
}
}
}
catch (Exception ex)
{
Debug.Write(ex);
Debug.Write(ex.Message);
}
finally
{
if (bthSocket != null)
bthSocket.Close();
device = null;
adapter = null;
}
}
}