Unity pc蓝牙和安卓蓝牙通信

这篇具有很好参考价值的文章主要介绍了Unity pc蓝牙和安卓蓝牙通信。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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客户端的代码

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模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • tcp通信,客户端服务端

    //TCP通信的流程 //服务器端(被动接受连接的角色) 1.创建一个用于监听的套接字         -监听:监听有客户端的连接         -套接字:这个套接字其实就是一个文件描述符 2.将这个监听文件描述符和本地的IP和端口绑定(IP和端口就是服务器的地址信息)         -客户端

    2024年02月09日
    浏览(31)
  • 【Unity】Socket网络通信(TCP) - 最基础的客户端通信流程

    这篇文章主要内容是客户端与服务器通信的内容,服务端代码可以看我的这一篇文章【Unity】Socket网络通信(TCP) - 最基础的C#服务端通信流程 客户端与服务器的整个流程比较相似,客户端会更加简单一些: 创建socket 连接服务器 收发消息 释放socket,关闭连接 和服务端创建

    2024年02月03日
    浏览(36)
  • C++实现客户端/服务端通信(一)

    存放协议族、端口和地址信息 sockaddr结构体为了统一地址结构的表示方法,统一接口函数,但是操作不方便,所以定义了等价的sockaddr_in结构体,其大小与sockaddr相同,可以强制转换为sockaddr 之所以搞两个结构体,可能是因为sockaddr可以用于IPV4,后续也可以用于IPV6,sockaddr_i

    2024年02月11日
    浏览(28)
  • TCP实现服务器和客户端通信

    目录 TCP介绍 代码实现 server(服务器端) 代码分析 client(客户端) 代码分析 结果展示 TCP (Transmission Control Protocol) 是一种面向连接的协议,用于在计算机网络中传输数据。TCP 可以确保数据的可靠传输,即使在网络环境不稳定的情况下也能够保证数据的完整性和顺序。以下是

    2024年02月15日
    浏览(44)
  • 简易TCP客户端和服务器端通信

    #includeiostream #include winsock2.h   #include ws2tcpip.h   #includestdlib.h using namespace std; #define  BUF_SIZE  1024 int main() {     cout \\\"客户端\\\" endl;     //设置Winsock版本,     WSADATA   wsaData;     if (WSAStartup(MAKEWORD(2, 2), wsaData) != 0)     {         cout \\\"error\\\" endl;         exit(1);     }     //创建通

    2024年04月29日
    浏览(35)
  • TongLINKQ(3):TongLINKQ客户端与服务端通信

    1 上传客户端安装包 2  设置环境变量 把TLQCli8/setp全部内容加到用户的.bash_proflile或者.profile中。 .bash_proflile或者.profile在用户根目录下,需要使用以下命令才能查看。 到用户根目录把TLQCli8/setp全部内容加到用户的.bash_proflile或者.profile中。 打开.bash_profile或者.profile 把TLCLIHOME

    2024年01月17日
    浏览(107)
  • QTday05(TCP的服务端客户端通信)

    pro文件需要导入  network 头文件: widget.cpp ui: 头文件 widget.cpp ui: 运行结果:客户端连接之后可以成功发送信息 今日思维导图: 代码: page2.h: widget.h: main.cpp: page2.cpp: widget.cpp: page2.ui: widget.ui: 运行结果:

    2024年02月07日
    浏览(28)
  • TCP通信实现客户端向服务器发送图片

    TCP通信: 1. TCP 协议通信交互流程: 具体的流程如下: (1)服务器根据地址类型(ipv4、ipv6)、socket 类型、协议创建 socket. (2)服务器为 socket 绑定 ip 地址和端口号。 (3)服务器 socket 监听端口号的请求,随时准备接受来自客户端的连接,此时服务器的 socket 处于关闭状态

    2024年02月13日
    浏览(45)
  • C++实现WebSocket通信(服务端和客户端)

    天行健,君子以自强不息;地势坤,君子以厚德载物。 每个人都有惰性,但不断学习是好好生活的根本,共勉! 文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。 这里单纯是个人总结,如需更官方更准确的websocket介绍可百度 websocket是一种即时通讯协

    2024年02月09日
    浏览(33)
  • UDP服务端和客户端通信代码开发流程

    TCP: 传输控制协议,面向连接的,稳定的,可靠的,安全的数据集流传递 稳定和可靠:丢包重传 数据有序:序号和确认序号 流量控制:稳定窗口 UDP :用户数据报协议 面向无连接的,不稳定的,不可靠,不安全的数据报传递=---更像是收发短信,UDP传输不需要建立连接,传输效率更高

    2024年02月06日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包