lvjincheng 4 年之前
父節點
當前提交
a1fec084b5
共有 2 個文件被更改,包括 96 次插入0 次删除
  1. 85 0
      Assets/Test9Axis/BleUDP.cs
  2. 11 0
      Assets/Test9Axis/BleUDP.cs.meta

+ 85 - 0
Assets/Test9Axis/BleUDP.cs

@@ -0,0 +1,85 @@
+using System.Collections;
+using System.Collections.Generic;
+using UnityEngine;
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+
+public class BleUDP : MonoBehaviour
+{
+    string localIP = "127.0.0.1";
+    int myPort = 8001;
+    int targetPort = 8000;
+    Socket client;
+    static BleUDP ins;
+
+    void Start()
+    {
+        if (ins != null)
+        {
+            DontDestroyOnLoad(this);
+            return;
+        }
+        ins = this;
+
+        client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+        client.Bind(new IPEndPoint(IPAddress.Parse(localIP), myPort));               
+        Thread threadSendMsg = new Thread(sendMsg);
+        threadSendMsg.Start();                          
+        Thread threadReciveMsg = new Thread(ReciveMsg);
+        threadReciveMsg.Start();
+    }
+
+    void OnDestroy()
+    {
+        if (ins == this) ins = null;
+        client.Close();
+    }
+
+    Queue<byte[]> byteQueue = new Queue<byte[]>();
+    void Update()
+    {
+        byte[] bytes = null;
+        lock (byteQueue)
+        {
+            if (byteQueue.Count > 0)
+            {
+                bytes = byteQueue.Dequeue();
+            }
+        }
+        if (bytes != null)
+        {
+            BluetoothClient.onDataReceived(0, bytes);
+        }
+    }
+
+    void sendMsg()
+    {
+        EndPoint point = new IPEndPoint(IPAddress.Parse(localIP), targetPort);
+        client.SendTo(Encoding.UTF8.GetBytes("1"), point);
+        Thread.Sleep(1000);
+        point = new IPEndPoint(IPAddress.Parse(localIP), targetPort);
+        client.SendTo(Encoding.UTF8.GetBytes("3"), point);
+        Thread.Sleep(1000);
+    }
+
+    void ReciveMsg()
+    {
+        while (true)
+        {
+            EndPoint point = new IPEndPoint(IPAddress.Any, 0);
+            byte[] buffer = new byte[1024];
+            int length = client.ReceiveFrom(buffer, ref point);
+            if (!point.ToString().EndsWith(targetPort.ToString())) return;
+            if (length <= 0) continue;
+            byte[] bytes = new byte[length];
+            Array.Copy(buffer, bytes, length);
+            lock (byteQueue)
+            {
+                byteQueue.Enqueue(bytes);
+            }
+        }
+    }
+}

+ 11 - 0
Assets/Test9Axis/BleUDP.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f546fdb70c8db2948b94181f917d807d
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: