Client.cs 25 KB

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