繁体   English   中英

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

[英]Bluetooth connection from phone to 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;
        }
    }
}

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

就是这样,我现在可以将手机连接到PC。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM