从电话到PC C#Xamarin.Forms的蓝牙连接

时间:2019-03-02 12:57:35

标签: c# android xamarin.forms bluetooth

开发人员们好!我目前正在从事一个项目,该项目需要从电话到计算机的蓝牙连接,并传输一些数据并将其输出到PuTTY上。但是问题是无论何时我想与套接字连接都会给我这个错误:

  

读取失败,套接字可能关闭或超时,读取ret:-1

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Bluetooth;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using BluetoothSample.Droid.PlatformSpecifics;
using BluetoothSample.Services.Interfaces;
using Java.Util;
using Xamarin.Forms;
using Debug = System.Diagnostics.Debug;

[assembly: Dependency(typeof(BluetoothService))]
namespace BluetoothSample.Droid.PlatformSpecifics
{
    public class BluetoothService : IBluetoothService
    {
        private CancellationTokenSource _cancellationToken { get; }

        public string MessageToSend { get; set; }

        public BluetoothService()
        {
            _cancellationToken = new CancellationTokenSource();
        }

        public void Connect(string name)
        {
            Task.Run(async () => await ConnectDevice(name));
        }

        private async Task ConnectDevice(string name)
        {
            BluetoothDevice device = null;
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
            BluetoothSocket bthSocket = null;

            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;

                            break;
                        }
                    }

                    if (device == null)
                        Debug.Write("Named device not found.");
                    else
                    {
                        UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");

                        bthSocket = device.CreateRfcommSocketToServiceRecord(uuid);

                        if (bthSocket != null)
                        {
                            adapter.CancelDiscovery();

                            await bthSocket.ConnectAsync();

                            if (bthSocket.IsConnected)
                            {
                                Debug.Write("Connected");

                                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;
                }
            }
        }

        public void Disconnect()
        {
            if (_cancellationToken != null)
            {
                _cancellationToken.Cancel();
            }
        }

        public List<string> PairedDevices()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
            List<string> devices = new List<string>();

            foreach (var bondedDevices in adapter.BondedDevices)
                devices.Add(bondedDevices.Name);

            return devices;
        }

        public void Send(string message)
        {
            if (MessageToSend == null)
                MessageToSend = message;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好的,所以我通过用以下代码块代替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;
                }
            }
        }

就是这样,现在我可以将手机连接到我的电脑了。