Client.cs 24 KB

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