首页 > 解决方案 > 从手机到 PC C# Xamarin.Forms 的蓝牙连接

问题描述

美好的一天开发者!我目前正在做一个项目,该项目需要从手机到计算机的蓝牙连接,并传输一些数据并将其输出到 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;
        }
    }
}

标签: c#androidxamarin.formsbluetooth

解决方案


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

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


推荐阅读