|
|
@@ -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);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|