123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- using LitJson;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using UnityEngine;
- public class BlueUdp : MonoBehaviour
- {
- public delegate void logMessagaeBarScanResultDelegat(string message);
- public static logMessagaeBarScanResultDelegat logMBSRD;
-
- string AddressIP;
- Socket socket;
- EndPoint serverEnd;
- IPEndPoint ipEnd;
- IPEndPoint ipSocketEnd;
- string recvStr;
- string sendStr;
- byte[] recvData = new byte[4096];
- byte[] sendData = new byte[4096];
- int recvLen;
- Thread connectThread;
-
- void InitSocket()
- {
-
-
- ipSocketEnd = new IPEndPoint(IPAddress.Parse("192.168.3.67"), 9981);
-
- ipEnd = new IPEndPoint(IPAddress.Parse(AddressIP), 9981);
-
-
- socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- socket.Bind(ipEnd);
-
- IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
- serverEnd = (EndPoint)sender;
-
- SocketSend("hello");
-
- connectThread = new Thread(new ThreadStart(SocketReceive));
- connectThread.Start();
- }
- void SocketSend(string sendStr)
- {
-
- sendData = new byte[4096];
-
- sendData = Encoding.ASCII.GetBytes(sendStr);
-
- socket.SendTo(sendData, sendData.Length, SocketFlags.None, ipSocketEnd);
- }
-
- void SocketReceive()
- {
-
- while (true)
- {
- Debug.Log("1111111111111111111");
-
- recvData = new byte[4096];
-
- recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
-
-
- Debug.Log("2222222222222222222222222");
- recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
-
- Debug.Log(recvStr + "Idear");
- TestJsonManage.state = true;
- TestJsonManage.result = recvStr.Trim();
-
-
- }
- }
-
- void SocketQuit()
- {
-
- if (connectThread != null)
- {
- connectThread.Interrupt();
- connectThread.Abort();
- }
-
- if (socket != null)
- socket.Close();
- }
-
- void Start()
- {
-
- for (int i = 0; i < Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length; i++)
- {
- if (Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].AddressFamily.ToString() == "InterNetwork")
- {
- AddressIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].ToString();
- }
- }
- InitSocket();
- SendIpToBluetooth();
- }
-
- void Update()
- {
- }
- public void SendIpToBluetooth()
- {
- SendNetConnectProtocolBlue sendNet = new SendNetConnectProtocolBlue();
- sendNet.Tagid = DeviceSN.Instance.SendSerialBy16();
- sendNet.Port = 9981;
- sendNet.ProjectId = 44;
- string jsonData = JsonMapper.ToJson(sendNet);
- Debug.Log(jsonData);
- SocketSend(jsonData);
- }
- void OnApplicationQuit()
- {
- SocketQuit();
- }
- }
|