Client.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. using System.Linq;
  2. using UnityEngine;
  3. using UnityEngine.Networking;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Net.Sockets;
  7. using System.Net;
  8. using System.Text;
  9. using System;
  10. public class Client : MonoBehaviour
  11. {
  12. public const int socketPort = 87;
  13. public const int webglPort = 86;
  14. public uint account_id = 0; //id акка
  15. string ACCOUNT_NAME = "";
  16. bool login_sent;
  17. bool entered = false;
  18. bool dc = false;
  19. bool connected = false;
  20. int lag = 0;
  21. double last_ping_time = 0;
  22. static string[] Servers = { "dev.prmsys.net", "localhost", "corp.prmsys.net" };
  23. static bool ShowPacketsSent = true;
  24. //private const bool ShowPacketsSent = false;
  25. // private const bool ShowPackets = true; //ставится только в редакторе
  26. static bool ShowPackets = false; //ставится только в редакторе
  27. double initial_timer;
  28. int internal_timer = 0;
  29. internal void SendGetUsers(object p)
  30. {
  31. throw new NotImplementedException();
  32. }
  33. public double timer
  34. {
  35. get
  36. {
  37. return DateTime.Now.Ticks / 10000000.0; //секунды
  38. }
  39. }
  40. public static Client instance;
  41. public static string ServerName;
  42. public static bool StartConnectFlag = false;
  43. #if UNITY_WEBGL
  44. public static WebSocket Mysocket;
  45. #else
  46. public static Socket Mysocket;
  47. #endif
  48. Dictionary<int, int> PacketLength = new Dictionary<int, int>();
  49. public delegate void OnReceive(byte[] bytedata);
  50. public static OnReceive[] packets = new OnReceive[255];
  51. private static Dictionary<string, UnityEngine.Object> loaded_models = new Dictionary<string, UnityEngine.Object>();
  52. private static Dictionary<string, UnityEngine.Object> loaded_icons = new Dictionary<string, UnityEngine.Object>();
  53. public string _dataPath = "";
  54. GameObject drone;
  55. public static ClientType clientType;
  56. public enum ClientType
  57. {
  58. Desktop,
  59. Web
  60. }
  61. public static void SendEnqueue(byte[] bytedata)
  62. {
  63. SendQueue.Enqueue(bytedata);
  64. }
  65. private void Awake()
  66. {
  67. instance = this;
  68. ServerName = PlayerPrefs.GetString("server");
  69. if (ServerName == "")
  70. ServerName = Servers[0];
  71. Register(1, Disconnect, 5);
  72. Register(2, Login, 5);
  73. Register(3, CoordinatesReceive);
  74. Register(30, Myping, 3);
  75. Register(47, UsersReceive);
  76. Register(48, BeaconsReceive);
  77. //set data path
  78. //if (Application.platform == RuntimePlatform.WindowsWebPlayer ||
  79. // Application.platform == RuntimePlatform.OSXWebPlayer)
  80. if (Application.platform == RuntimePlatform.WebGLPlayer)
  81. {
  82. _dataPath = Application.dataPath + "/StreamingAssets";
  83. clientType = ClientType.Web;
  84. }
  85. else if (Application.platform == RuntimePlatform.Android)
  86. {
  87. _dataPath = "jar:file://" + Application.dataPath + "!/assets";
  88. clientType = ClientType.Web;
  89. }
  90. else
  91. {
  92. _dataPath = "file://" + Application.dataPath + "/StreamingAssets"; ;
  93. clientType = ClientType.Desktop;
  94. }
  95. _dataPath = Application.streamingAssetsPath;
  96. //Debug.Log("_dataPath " + _dataPath);
  97. }
  98. public int LagCount
  99. {
  100. get
  101. {
  102. return lagpoints.Count;
  103. }
  104. }
  105. int totallag
  106. {
  107. get
  108. {
  109. int q = 0;
  110. foreach (var g in lagpoints)
  111. {
  112. q += g;
  113. }
  114. return q;
  115. }
  116. }
  117. Queue<int> lagpoints = new Queue<int>();
  118. public int Averagelag
  119. {
  120. get
  121. {
  122. if (lagpoints.Count > 0)
  123. return totallag / lagpoints.Count;
  124. return 0;
  125. }
  126. }
  127. public void CoordinatesReceive(byte[] bytedata)
  128. {
  129. //var coordleng = bytedata.Length - 11;
  130. var accid = BitConverter.ToUInt32(bytedata, 5);
  131. var locid = BitConverter.ToUInt32(bytedata, 9);
  132. //WorkerController.TestStructures.Clear();
  133. //print("len " + BitConverter.ToUInt32(bytedata, 1));
  134. var worker = new List<Structure>();
  135. for (var read = 13; read < bytedata.Length; read += 20)
  136. {
  137. var id = BitConverter.ToUInt32(bytedata, read);
  138. var x = BitConverter.ToInt32(bytedata, read+4);
  139. var y = BitConverter.ToInt32(bytedata, read+8);
  140. var ticks = BitConverter.ToInt64(bytedata, read+12);
  141. //print($"coord accid {accid} locid {locid} {id} x {x} y{y} ticks {ticks}");
  142. //WorkerController.markers.ElementAt(1).marker.transform.position = new Vector3(x, 0.5f, y);
  143. //WorkerController.TestStructures
  144. worker.Add(new Structure
  145. {
  146. id = id,
  147. coord_x = x,
  148. coord_y = y,
  149. ts = new DateTime(ticks),
  150. acc_id = accid,
  151. location_id = locid,
  152. zone_id = 1
  153. });
  154. }
  155. WorkerController.Workers[accid] = worker;
  156. WorkerController.end_send[accid] = true;
  157. }
  158. public void Myping(byte[] bytedata)
  159. {
  160. last_ping_time = timer;
  161. int lag = BitConverter.ToUInt16(bytedata, 1);
  162. //print("Myping " + lag);
  163. this.lag = lag;
  164. if (lagpoints.Count > 5)
  165. lagpoints.Dequeue();
  166. lagpoints.Enqueue(lag);
  167. List<byte> list = new List<byte>();
  168. list.Add(30);
  169. list.Add((byte)1);
  170. SendEnqueue(list.ToArray());
  171. }
  172. public void Disconnect(byte[] bytedata)
  173. {
  174. uint bid = BitConverter.ToUInt32(bytedata, 1);
  175. if (bid == account_id)
  176. Exit();
  177. else
  178. {
  179. print("disc id " + bid);
  180. }
  181. }
  182. public void Exit()
  183. {
  184. print("Client Exit");
  185. connected = false;
  186. login_sent = false;
  187. if (Mysocket != null)
  188. {
  189. Mysocket.Close();
  190. Mysocket = null;
  191. }
  192. connect_started = new DateTime();
  193. totalbytes = 0;
  194. account_id = 0;
  195. ACCOUNT_NAME = "";
  196. connected = false;
  197. sendDone = false;
  198. receiveDone = false;
  199. connectDone = false;
  200. StartConnectFlag = false;
  201. UnityEngine.SceneManagement.SceneManager.LoadScene(0);
  202. }
  203. //пакет с 1 параметром = 1
  204. public static void SendOneBytePacket(int num)
  205. {
  206. SendOneByteParamPacket(num, 1);
  207. }
  208. public static void SendOneByteTwoParamsPacket(int num, int param1, int param2)
  209. {
  210. byte[] data = { (Byte)num, (Byte)param1, (byte)param2 };
  211. SendEnqueue(data);
  212. }
  213. public static void SendThreeParamsIntPacket(int num, int param1, int param2, int param3)
  214. {
  215. List<byte> list = new List<byte>();
  216. list.Add((Byte)num);
  217. list.AddRange(BitConverter.GetBytes(param1));
  218. list.AddRange(BitConverter.GetBytes(param2));
  219. list.AddRange(BitConverter.GetBytes(param3));
  220. SendEnqueue(list.ToArray());
  221. }
  222. //пакет с 1 1-байтовым параметром
  223. public static void SendOneByteParamPacket(int num, int param)
  224. {
  225. byte[] data = { (Byte)num, (Byte)param };
  226. byteSend(data);
  227. }
  228. //пакет с 1 4-байтовым параметром
  229. public static void SendTwoByteParamPacket(int num, ushort param)
  230. {
  231. List<byte> list = new List<byte>();
  232. list.Add((Byte)num);
  233. list.AddRange(BitConverter.GetBytes(param));
  234. SendEnqueue(list.ToArray());
  235. }
  236. //пакет с 1 4-байтовым параметром
  237. public static void SendFourByteParamPacket(int num, uint param)
  238. {
  239. List<byte> list = new List<byte>();
  240. list.Add((Byte)num);
  241. list.AddRange(BitConverter.GetBytes(param));
  242. SendEnqueue(list.ToArray());
  243. }
  244. public static DateTime connect_started;
  245. public void Login(byte[] bytedata)
  246. {
  247. uint accid = BitConverter.ToUInt32(bytedata, 1);
  248. if (accid == 0xFFFFFFFF)
  249. {
  250. Debug.LogError("Login or password incorrect");
  251. AuthorizationController.error = true;
  252. return;
  253. }
  254. else if (accid == 0xFFFFFFFE)
  255. {
  256. Debug.LogError("Account was already connected");
  257. return;
  258. }
  259. else if (accid == 0xFFFFFFFD)
  260. {
  261. Debug.LogError("Incorrect client version");
  262. return;
  263. }
  264. AuthorizationController.success = true;
  265. account_id = accid;
  266. //var ts = DateTime.Now.Ticks-1000000000000;
  267. //var te = DateTime.Now.Ticks;
  268. //CoordinatesRequest(ts, te, 1, 1);
  269. SendGetUsers(1);
  270. }
  271. #region system functions
  272. public void Register(int packnum, OnReceive func)
  273. {
  274. packets[packnum] = func;
  275. }
  276. private void Register(int packnum, OnReceive func, int len)
  277. {
  278. packets[packnum] = func;
  279. if (len > 1)
  280. PacketLength[packnum] = len;
  281. }
  282. public int GetLength(byte[] data, int num, int offset)
  283. {
  284. int leng;
  285. if (!PacketLength.ContainsKey(num))
  286. {
  287. var rest = data.Length - offset;
  288. //packet not full
  289. if (rest < 5)
  290. return 1;
  291. leng = BitConverter.ToInt32(data, offset + 1);
  292. }
  293. else
  294. leng = PacketLength[num];
  295. //Debug.Log("GetLength " + leng);
  296. return leng;
  297. }
  298. int maximumPacketsPerUpdate = 50;
  299. public void Start()
  300. {
  301. entered = true;
  302. }
  303. public void Update()
  304. {
  305. #if UNITY_WEBGL
  306. Receive();
  307. #endif
  308. if (instance == null || !entered) //вход не нажат, ждем
  309. {
  310. return;
  311. }
  312. else
  313. {
  314. if (!StartConnectFlag)
  315. {
  316. StartCoroutine(Connect());
  317. StartConnectFlag = true;
  318. }
  319. }
  320. if(AuthorizationController.send)SendLogin();
  321. int from_connect = DateTime.Now.Subtract(connect_started).Seconds;
  322. if (from_connect > 7 && from_connect != DateTime.Now.Second && account_id == 0)
  323. {
  324. Exit();
  325. }
  326. var processedCount = 0;
  327. while (PacketQueue.Count > 0 && processedCount < maximumPacketsPerUpdate) //если длина очереди с пакетами ==0
  328. {
  329. byte[] packetbytes;
  330. lock (packetqueuelock)
  331. {
  332. packetbytes = PacketQueue.Dequeue();
  333. }
  334. int offset = 0;
  335. int totallen = 0;
  336. int num = (int)packetbytes[0];
  337. int leng = GetLength(packetbytes, packetbytes[0], 0);
  338. if (leng <= packetbytes.Length)
  339. {
  340. while (offset < packetbytes.Length)
  341. {
  342. num = (int)packetbytes[offset];
  343. leng = GetLength(packetbytes, num, offset);
  344. totallen += leng;
  345. print("num " + num + " leng " + leng);
  346. byte[] newpack = new byte[leng];
  347. Array.Copy(packetbytes, offset, newpack, 0, leng);
  348. offset += leng;
  349. if (ShowPackets)
  350. {
  351. if (num != 30) //не пакет пинга
  352. {
  353. //string mygg = packets[num].Method.Name + " "; //Печатаем принятые байты!
  354. string mygg = "";
  355. foreach (byte b in newpack)
  356. {
  357. mygg += b + " ";
  358. }
  359. //Debug.Log("ticks " + DateTime.Now.Ticks / 10000 + " timesince " + Time.timeSinceLevelLoad +" "+ newpack.Length + " bytes packet: " + mygg);
  360. Debug.Log(newpack.Length + " bytes packet: " + mygg);
  361. }
  362. }
  363. processedCount++;
  364. packets[num](newpack);//запустить OnReceive функцию
  365. //print("copy "+num);
  366. }
  367. }
  368. }
  369. //Debug.Log("Update End");
  370. }
  371. public void LateUpdate()
  372. {
  373. while (SendQueue.Count > 0)
  374. {
  375. //print("SendQueue.Count " + SendQueue.Count);
  376. byte[] sendstring = SendQueue.Dequeue();
  377. //print("sendstring len " + sendstring.Length);
  378. byteSend(sendstring);
  379. }
  380. }
  381. public class StateObject
  382. {
  383. // Client socket.
  384. // Size of receive buffer.
  385. public const int BufferSize = 128000;
  386. // Receive buffer.
  387. public byte[] buffer = new byte[BufferSize];
  388. // Received data string.
  389. }
  390. public static Queue<byte[]> PacketQueue = new Queue<byte[]>();
  391. static Queue<byte[]> SendQueue = new Queue<byte[]>();
  392. public static bool receiveDone, connectDone, sendDone = false;
  393. public static StateObject state = new StateObject();
  394. private IEnumerator Connect()
  395. {
  396. Debug.Log("Connect");
  397. // Connect to a remote server.
  398. #if UNITY_WEBGL
  399. var uristring = $"ws://{ServerName}:{webglPort}/ws";
  400. Debug.Log($"WebSocket tryconnect: {uristring}");
  401. WebSocket client = new WebSocket(new Uri(uristring));
  402. Mysocket = client;
  403. yield return StartCoroutine(Mysocket.Connect());
  404. connectDone = (Mysocket.error == null);
  405. if (!connectDone)
  406. {
  407. Debug.Log("WebSocket error: " + Mysocket.error);
  408. yield break;
  409. }
  410. #else
  411. // Establish the remote endpoint for the socket.
  412. /*IPAddress ip = */
  413. new IPAddress(new byte[] { 127, 0, 0, 1 });
  414. IPHostEntry ipHostInfo = Dns.GetHostEntry(ServerName);
  415. //string localHost = Dns.GetHostName();
  416. //print("localHost " + ipHostInfo.AddressList[0]);
  417. //IPHostEntry ipHostInfo = Dns.GetHostEntry(localHost);
  418. IPAddress[] ipv4Addresses = Array.FindAll(ipHostInfo.AddressList, a => a.AddressFamily == AddressFamily.InterNetwork);
  419. //print("localHost v4 " + ipv4Addresses[0]);
  420. // IPAddress ipAddress = ipHostInfo.AddressList[0];
  421. IPAddress ipAddress = ipv4Addresses[0];
  422. //IPEndPoint remoteEP = new IPEndPoint(ip, socketPort);
  423. IPEndPoint remoteEP = new IPEndPoint(ipAddress, socketPort);
  424. // Create a TCP/IP socket.
  425. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  426. //Socket client = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  427. print("remoteEP.AddressFamily " + AddressFamily.InterNetwork);
  428. print("client " + client.AddressFamily);
  429. Mysocket = client;
  430. // Connect to the remote endpoint.
  431. try
  432. {
  433. client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
  434. }
  435. catch (Exception e)
  436. {
  437. print(e.Message);
  438. }
  439. int num = 0;
  440. while (!connectDone && num < 10)
  441. {
  442. num++;
  443. yield return new WaitForSeconds(0.2f);
  444. }
  445. if (!connectDone)
  446. {
  447. print(socketPort + " port failed");
  448. yield break;
  449. }
  450. #endif
  451. print("connected");
  452. connected = true;
  453. while (true)
  454. {
  455. if (!entered)
  456. break;
  457. while (!sendDone && connected)
  458. {
  459. yield return 1;
  460. }
  461. Receive();
  462. while (!receiveDone && connected)
  463. {
  464. yield return 1;
  465. }
  466. receiveDone = false;
  467. break;
  468. }
  469. yield break;
  470. }
  471. private static void ConnectCallback(IAsyncResult ar)
  472. {
  473. // Retrieve the socket from the state object.
  474. Socket client = (Socket)ar.AsyncState;
  475. connect_started = DateTime.Now;
  476. // Complete the connection.
  477. try
  478. {
  479. client.EndConnect(ar);
  480. }
  481. catch (Exception e)
  482. {
  483. print(e.Message);
  484. }
  485. // Signal that the connection has been made.
  486. connectDone = true;
  487. }
  488. private void Receive()
  489. {
  490. #if UNITY_WEBGL
  491. CheckWebSocket();
  492. if (Mysocket == null)
  493. return;
  494. byte[] packet = null;
  495. do
  496. {
  497. packet = Mysocket.Recv();
  498. if (packet != null)
  499. {
  500. lock (packetqueuelock)
  501. {
  502. PacketQueue.Enqueue(packet);
  503. }
  504. receiveDone = true;
  505. totalbytes += packet.Length;
  506. }
  507. }
  508. while (packet != null);
  509. #else
  510. Mysocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  511. new AsyncCallback(ReceiveCallback), state);
  512. #endif
  513. }
  514. public static object packetqueuelock = new object();
  515. public static Queue<byte[]> tempqueue = new Queue<byte[]>();
  516. public bool CheckLength(byte[] packetbytes)
  517. {
  518. if (packetbytes.Length > 0) //если длина очереди с пакетами ==0
  519. {
  520. int offset = 0;
  521. //TODO проверка на мусор
  522. int num = packetbytes[0];
  523. int leng = GetLength(packetbytes, packetbytes[0], 0);
  524. if (leng <= packetbytes.Length)
  525. {
  526. while (offset < packetbytes.Length)
  527. {
  528. num = packetbytes[offset];
  529. leng = GetLength(packetbytes, num, offset);
  530. if (leng == 1)
  531. {
  532. print("Error: CheckLength: packet not complete");
  533. return false;
  534. }
  535. //print("Checking Length of " + num + " len " + leng);
  536. if (leng == 0)
  537. {
  538. print("CheckLength2 break! length error " + num);
  539. dc = true;
  540. break;
  541. }
  542. offset += leng;
  543. }
  544. }
  545. if (offset == packetbytes.Length)
  546. return true;
  547. return false;
  548. }
  549. return false;
  550. }
  551. public static int totalbytes = 0;
  552. #if !UNITY_WEBGL
  553. private void ReceiveCallback(IAsyncResult ar) //TODO если приходят данные больше длины буфера, пакеты режутся на части и складываются в обратном порядке - fix, пока что увеличим буфер
  554. {
  555. // Retrieve the state object and the client socket
  556. // from the asynchronous state object.
  557. StateObject state = (StateObject)ar.AsyncState;
  558. // Read data from the remote device.
  559. int bytesRead = 0;
  560. bytesRead = Mysocket.EndReceive(ar);
  561. if (bytesRead > 0)
  562. {
  563. // All the data has arrived; put it in response.
  564. byte[] newbuf = new Byte[bytesRead];
  565. Array.Copy(state.buffer, newbuf, bytesRead);
  566. //if (ShowPackets)
  567. //{
  568. // if (newbuf[0] != 30) //не пакет пинга
  569. // {
  570. // string mygg = ""; //Печатаем принятые байты!
  571. // foreach (byte b in newbuf)
  572. // {
  573. // mygg += b + " ";
  574. // }
  575. // print(newbuf.Length + " bytes: " + mygg);
  576. // }
  577. // totalbytes += bytesRead;
  578. //}
  579. byte[] tocheck = newbuf;
  580. if (tempqueue.Count > 0)
  581. {
  582. Queue<byte[]> myqueue = new Queue<byte[]>(tempqueue);
  583. List<byte> list = new List<byte>();
  584. while (myqueue.Count > 0)
  585. {
  586. list.AddRange(myqueue.Dequeue());
  587. }
  588. list.AddRange(newbuf);
  589. tocheck = list.ToArray();
  590. }
  591. if (!CheckLength(tocheck))
  592. {
  593. tempqueue.Clear();
  594. tempqueue.Enqueue(tocheck);
  595. }
  596. else
  597. {
  598. tempqueue.Clear();
  599. lock (packetqueuelock)
  600. {
  601. PacketQueue.Enqueue(tocheck);
  602. }
  603. }
  604. receiveDone = true;
  605. Receive();
  606. }
  607. }
  608. #endif
  609. #if UNITY_WEBGL
  610. private static void CheckWebSocket()
  611. {
  612. if (Mysocket != null && Mysocket.error != null)
  613. {
  614. Debug.LogError(Mysocket.error);
  615. instance.Exit();
  616. }
  617. }
  618. #endif
  619. private static void byteSend(byte[] tosend)
  620. {
  621. if (tosend == null)
  622. {
  623. Debug.LogError("tosend null");
  624. return;
  625. }
  626. if (ShowPacketsSent)
  627. {
  628. byte[] newbuf = new Byte[tosend.Length];
  629. Array.Copy(tosend, newbuf, tosend.Length);
  630. if (newbuf[0] != 30) //не пакет пинга
  631. {
  632. string mygg = "sent: "; //Печатаем отправленные байты!
  633. foreach (byte b in newbuf)
  634. {
  635. mygg += b + " ";
  636. }
  637. print(newbuf.Length + " bytes: " + mygg);
  638. }
  639. }
  640. #if UNITY_WEBGL
  641. byte[] webglbuf = new Byte[tosend.Length];
  642. Array.Copy(tosend, webglbuf, tosend.Length);
  643. CheckWebSocket();
  644. if (Mysocket != null)
  645. {
  646. Mysocket.Send(webglbuf);
  647. sendDone = true;
  648. Debug.Log("websocket sendDone");
  649. }
  650. #else
  651. try
  652. {
  653. //print("buffer size " + Mysocket.SendBufferSize + " tosend.Length " + tosend.Length);
  654. Mysocket.BeginSend(tosend, 0, tosend.Length, 0, SendCallback, Mysocket);
  655. }
  656. catch (Exception e)
  657. {
  658. if (instance != null)
  659. {
  660. print(e.Message);
  661. instance.Exit();
  662. }
  663. }
  664. #endif
  665. }
  666. #if !UNITY_WEBGL
  667. private static void SendCallback(IAsyncResult ar)
  668. {
  669. // Retrieve the socket from the state object.
  670. Socket client = (Socket)ar.AsyncState;
  671. // Complete sending the data to the remote device.
  672. /*int bytesSent = */
  673. client.EndSend(ar);
  674. //print("Sent " + bytesSent + " bytes to server.");
  675. // Signal that all bytes have been sent.
  676. sendDone = true;
  677. }
  678. #endif
  679. #endregion
  680. public static string GetMD5Hash(string input)
  681. {
  682. System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
  683. byte[] bs = Encoding.UTF8.GetBytes(input);
  684. bs = x.ComputeHash(bs);
  685. StringBuilder s = new StringBuilder();
  686. foreach (byte b in bs)
  687. {
  688. s.Append(b.ToString("x2").ToLower());
  689. }
  690. string password = s.ToString();
  691. return password;
  692. }
  693. /// <summary>
  694. /// Запрос координат с сервера, timeStart, timeEnd == DateTime.Ticks
  695. /// </summary>
  696. public void CoordinatesRequest(long timeStart, long timeEnd, byte resolution, uint locationID, uint account_id)
  697. {
  698. login_sent = true;
  699. Debug.Log("SendRequestCoordinates");
  700. List<byte> list = new List<byte>();
  701. list.Add(3);
  702. list.AddRange(BitConverter.GetBytes(account_id));
  703. list.AddRange(BitConverter.GetBytes(timeStart));
  704. list.AddRange(BitConverter.GetBytes(timeEnd));
  705. list.Add(resolution);
  706. list.AddRange(BitConverter.GetBytes(locationID));
  707. SendEnqueue(list.ToArray());
  708. }
  709. //companyId: 1 = Тайшет, 2 = Тестовая, 3 = Братское
  710. public void SendGetUsers(uint companyId)
  711. {
  712. List<byte> list = new List<byte>();
  713. list.Add(47);
  714. list.AddRange(BitConverter.GetBytes(companyId));
  715. SendEnqueue(list.ToArray());
  716. }
  717. public void UsersReceive(byte[] bytedata)
  718. {
  719. print("UsersReceive");
  720. WorkerController.users = new List<User>();
  721. int read = 5;
  722. while (read < bytedata.Length)
  723. {
  724. var id = BitConverter.ToUInt32(bytedata, read);
  725. var lenname = bytedata[read+4];
  726. var name = Encoding.UTF8.GetString(bytedata, read+5, lenname);
  727. read += 5 + lenname;
  728. //print($"user received id {id} lenname {lenname} name {name}");
  729. WorkerController.users.Add(new User { id = id, name = name });
  730. }
  731. WorkerController.users_load = true;
  732. }
  733. public void BeaconsReceive(byte[] bytedata)
  734. {
  735. int read = 5;
  736. while (read < bytedata.Length)
  737. {
  738. var id = BitConverter.ToUInt32(bytedata, read);
  739. var uuid = Encoding.UTF8.GetString(bytedata, read + 4, 36);
  740. var x = BitConverter.ToSingle(bytedata, read + 40);
  741. var y = BitConverter.ToSingle(bytedata, read + 44);
  742. var z = BitConverter.ToSingle(bytedata, read + 48);
  743. var minor = BitConverter.ToUInt16(bytedata, read + 52);
  744. var major = BitConverter.ToUInt16(bytedata, read + 54);
  745. print($"beacon received id {id} uuid {uuid} x {x} y {y} z {z} minor {minor} major {major}");
  746. read += 56;
  747. WorkerController.Beacons.Add(new Beacon { id = id, uuid = uuid, x = x, y = y, z = z, minor = minor, major = major });
  748. }
  749. WorkerController.beacons_load = true;
  750. }
  751. public void BeaconsRequest(uint locationId)
  752. {
  753. Debug.Log("BeaconsRequest connected "+ connected);
  754. //if (!connected)
  755. //{
  756. // return;
  757. //}
  758. SendFourByteParamPacket(48, locationId);
  759. }
  760. public void SendLogin()
  761. {
  762. if (!connected)
  763. {
  764. //Debug.LogError("Couldn't connect");
  765. //Exit();
  766. return;
  767. }
  768. if (!login_sent)
  769. {
  770. login_sent = true;
  771. Debug.Log("SendLogin");
  772. string passwordToEdit = AuthorizationController.password;// "8*9Efc2%";
  773. string login = AuthorizationController.login;//"vsheiko";
  774. string pass = GetMD5Hash(passwordToEdit);
  775. byte[] bpass = Encoding.UTF8.GetBytes(pass);
  776. byte[] blogin = Encoding.UTF8.GetBytes(login);
  777. List<byte> list = new List<byte>();
  778. byte loginFlag = 1;
  779. int leng = (bpass.Length + blogin.Length + 6); //+имя+длина
  780. list.Add(2);
  781. list.AddRange(BitConverter.GetBytes(leng));
  782. list.Add(loginFlag);
  783. list.AddRange(bpass);
  784. list.AddRange(blogin);
  785. SendEnqueue(list.ToArray());
  786. }
  787. }
  788. }