Client.cs 31 KB

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