Client.cs 25 KB

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