Client.cs 29 KB

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