pc是客户端,安卓是服务端。
pc端需要拖入一个 InTheHand.Net.Bluetooth.dll 文件放在Plugins文件夹里。dll文件下载链接
pc端参考资料
https://blog.csdn.net/oqzuser12345678923/article/details/51252545/
http://t.zoukankan.com/buptzym-p-2169858.html
安卓端使用是 NativeBT 插件,这个插件网上就可以下载
下面是pc客户端的代码文章来源:https://www.toymoban.com/news/detail-512334.html
using UnityEngine;
using System.Threading;
using System;
using System.IO;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;
public class PC_BLT : MonoBehaviour
{
// 80:19:31:8C:6B:22
//F0:C8:14:33:8B:99
private Thread ReceiveThread;
private BluetoothClient bluetoothClient = null;
private Stream peerStream;
public byte[] buffer = new byte[128]; //接收数据
private bool isConnecting = true;
private BluetoothAddress sendAddress = new BluetoothAddress(new byte[] { 0x22, 0x6B, 0x8C, 0x31, 0x19, 0x80 }); //发送目的地址 地址要反着写
// Start is called before the first frame update
void Start()
{
BluetoothRadio bluetoothRadio = BluetoothRadio.Default;
if (bluetoothRadio == null)
{
Debug.Log("没有找到本机蓝牙设备!");
}
else
{
Debug.Log("ClassOfDevice: " + bluetoothRadio);
Debug.Log("Name: " + bluetoothRadio.Name);
Debug.Log(bluetoothRadio.LocalAddress);
Debug.Log(bluetoothRadio.LmpSubversion);
Guid guid = BluetoothService.Handsfree;
Debug.Log(guid);
}
Console.ReadKey();
OpenPort();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
WriteMethod();
}
}
/// <summary>
/// 打开端口
/// </summary>
/// <param name="Name">端口名称</param>
/// <returns>成功否</returns>
public bool OpenPort()
{
BluetoothRadio.Default.Mode = RadioMode.Connectable;
bluetoothClient = new BluetoothClient();
Guid mGUID = Guid.Parse("c1db6770-a359-11e6-80f5-76304dec7eb7");
// mGUID2 = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");
//bluetoothClient.Connect(sendAddress, mGUID2);//客户端对地址实现连接,这是一个阻塞线程,需要服务器端的回应
bluetoothClient.Connect(sendAddress, mGUID);//客户端对地址实现连接,这是一个阻塞线程,需要服务器端的回应
if (bluetoothClient.Connected)
{
Debug.Log("连接成功");
if (ReceiveThread != null && ReceiveThread.IsAlive)
{
ReceiveThread.Abort();
}
ReceiveThread = new Thread(new ThreadStart(ReceiveMethod));
ReceiveThread.Start();
}
else
{
Debug.Log("连接未成功");
}
return true;
}
/// <summary>
/// 接收数据
/// </summary>
public void ReceiveMethod()
{
while (isConnecting)
{
try
{
peerStream = bluetoothClient.GetStream();
int a = peerStream.Read(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
isConnecting = false;
if (ReceiveThread != null && ReceiveThread.IsAlive)
{
ReceiveThread.Abort();
}
Debug.Log(ex);
}
}
}
/// <summary>
/// 发送数据
/// </summary>
public void WriteMethod()
{
byte[] data = new byte[3] { 0x0A, 0x02, 0x03};
peerStream.Write(data,0 , data.Length);
}
public void OnDestroy()
{
if (ReceiveThread != null && ReceiveThread.IsAlive)
{
ReceiveThread.Abort();
}
BluetoothRadio.Default.Mode = RadioMode.PowerOff;
if (bluetoothClient != null && bluetoothClient.Connected)
{
bluetoothClient.Dispose();
bluetoothClient.Close();
}
}
}
下面是安卓服务端代码文章来源地址https://www.toymoban.com/news/detail-512334.html
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using leithidev.unityassets.nativebt.android.entities;
public class BTChat : MonoBehaviour
{
public Text _connectedToText;
public Text _listeningOnText;
public Text _chatText;
public InputField _sendInputField;
public Text _sendText;
public PairedDeviceButton _pairedDeviceListButton;
public RectTransform _pairedDeviceList;
public RectTransform _btnDisconnect;
public RectTransform _btnPairedDevices;
public string uuid = "c1db6770-a359-11e6-80f5-76304dec7eb7";
// Use this for initialization
void Start()
{
NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTMessageReceived += OnMessageReceived;
NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTMessageSent += OnMessageSent;
NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTDeviceConnected += OnBtDeviceConnected;
NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTDeviceDisconnected += OnBtDeviceDisconnected;
NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTDeviceConnectingFailed += OnBTDeviceConnectingFailed;
this._pairedDeviceList.gameObject.SetActive(false);
this._btnDisconnect.gameObject.SetActive(false);
}
private void OnBTDeviceConnectingFailed(LWBluetoothDevice device)
{
this._connectedToText.text = "Connecting to " + device.GetName() + " failed!";
}
private void OnBtDeviceConnected(LWBluetoothDevice device)
{
this._connectedTo = device;
this._connectedToText.text = device.GetName();
this._btnDisconnect.gameObject.SetActive(true);
this._btnPairedDevices.gameObject.SetActive(false);
}
private void OnBtDeviceDisconnected(LWBluetoothDevice device)
{
this._connectedTo = null;
this._connectedToText.text = "";
this._btnDisconnect.gameObject.SetActive(false);
this._btnPairedDevices.gameObject.SetActive(true);
}
private void OnMessageSent(string msg)
{
this._chatText.text += "\n" + NativeBTRuntime.NBTR.BTWrapper.GetBTAdapter().GetName() + ": " + msg;
}
/// <summary>
/// 接收数据
/// </summary>
/// <param name="msg"></param>
private void OnMessageReceived(string msg)
{
Debug.Log("数据:" + msg + "长度:" + msg.Length);
if (msg.Length > 0)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
for (int i = 0; i < asciiEncoding.GetBytes(msg).Length; i++)
{
Debug.Log(asciiEncoding.GetBytes(msg)[i]);
}
}
//this._chatText.text += "\n" + this._connectedTo.GetName() + ": " + msg;
}
public void OnDisconnectButtonClicked()
{
NativeBTRuntime.NBTR.BTWrapper.Disconnect();
}
public void OnSendButtonClicked()
{
string msg = this._sendInputField.text;
this._sendInputField.text = "";
NativeBTRuntime.NBTR.BTWrapper.Send(msg + System.Environment.NewLine);
}
public void OnPairedDeviceButtonClicked(LWBluetoothDevice btDevice)
{
NativeBTRuntime.NBTR.BTWrapper.Connect(btDevice, this.uuid);
this._pairedDeviceList.gameObject.SetActive(false);
}
public void OnPairedDevicesClicked()
{
if (!NativeBTRuntime.NBTR.BTWrapper.GetBTAdapter().IsEnabled())
{
NativeBTRuntime.NBTR.BTWrapper.ShowBTEnableRequest();
}
else
{
IList<LWBluetoothDevice> devices = NativeBTRuntime.NBTR.BTWrapper.GetPairedDevices();
this._pairedDeviceList.gameObject.SetActive(true);
this.ClearPairedDevicesList();
if (devices.Count == 0)
{
this._pairedDeviceList.gameObject.SetActive(false);
}
foreach (LWBluetoothDevice device in devices)
{
PairedDeviceButton pdb = Instantiate<PairedDeviceButton>(this._pairedDeviceListButton);
pdb._device = device;
pdb.GetComponent<Button>().GetComponentInChildren<Text>().text = device.GetName() + "|" + device.GetAddress();
pdb.GetComponent<Button>().onClick.AddListener(() => OnPairedDeviceButtonClicked(pdb._device));
pdb.transform.SetParent(this._pairedDeviceList);
}
}
}
private void ClearPairedDevicesList()
{
IList<GameObject> objsToDestroy = new List<GameObject>();
for (int x = 0; x < this._pairedDeviceList.transform.childCount; x++)
{
objsToDestroy.Add(this._pairedDeviceList.transform.GetChild(x).gameObject);
}
foreach (GameObject go in objsToDestroy)
{
Destroy(go);
}
}
public void OnListenClicked()
{
NativeBTRuntime.NBTR.BTWrapper.Disconnect();
if (!NativeBTRuntime.NBTR.BTWrapper.GetBTAdapter().IsEnabled())
{
NativeBTRuntime.NBTR.BTWrapper.ShowBTEnableRequest();
}
else
{
NativeBTRuntime.NBTR.BTWrapper.Listen(true, this.uuid);
this._listeningOnText.text = "Listen on: " + uuid;
}
}
private LWBluetoothDevice _connectedTo;
}
到了这里,关于Unity pc蓝牙和安卓蓝牙通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!