123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864 |
- using System.Linq;
- using UnityEngine;
- using UnityEngine.Networking;
- using System.Collections;
- using System.Collections.Generic;
- using System.Net.Sockets;
- using System.Net;
- using System.Text;
- using System;
- using UnityEngine.UI;
- public class Client : MonoBehaviour
- {
- public static Client instance;
- public const int socketPort = 87;
- public const int webglPort = 86;
- public uint account_id = 0;
- public uint company_id;
- string ACCOUNT_NAME = "";
- bool login_sent;
- bool entered = false;
- bool dc = false;
- public bool connected = false;
- int lag = 0;
- double last_ping_time = 0;
- static string[] Servers = { "dev.prmsys.net", "localhost", "corp.prmsys.net" };
- static bool ShowPacketsSent = false;
-
-
- static bool ShowPackets = false;
- double initial_timer;
- int internal_timer = 0;
- public double timer
- {
- get
- {
- return DateTime.Now.Ticks / 10000000.0;
- }
- }
- public static string ServerName;
- public static bool StartConnectFlag = false;
- #if UNITY_WEBGL
- public static WebSocket Mysocket;
- #else
- public static Socket Mysocket;
- #endif
- Dictionary<int, int> PacketLength = new Dictionary<int, int>();
- public delegate void OnReceive(byte[] bytedata);
- public static OnReceive[] packets = new OnReceive[255];
- public string _dataPath = "";
- GameObject drone;
- public static ClientType clientType;
- public enum ClientType
- {
- Desktop,
- Web
- }
- public static void SendEnqueue(byte[] bytedata)
- {
- SendQueue.Enqueue(bytedata);
- }
- private void Awake()
- {
- instance = this;
- ServerName = PlayerPrefs.GetString("server");
- if (ServerName == "")
- ServerName = Servers[0];
- Register(1, Disconnect, 5);
- Register(2, Login, 9);
- Register(3, User.CoordinatesReceive);
- Register(30, Myping, 3);
- Register(47, User.Receive);
- Register(48, Beacon.Receive);
- Register(51, Wall.ReceiveFromServer);
- Register(52, Zone.ReceiveFromServer);
- Register(54, Location.ReceiveFromServer);
- Register(55, ImgReceive);
-
-
-
- if (Application.platform == RuntimePlatform.WebGLPlayer)
- {
- _dataPath = Application.dataPath + "/StreamingAssets";
- clientType = ClientType.Web;
- }
- else if (Application.platform == RuntimePlatform.Android)
- {
- _dataPath = "jar:file://" + Application.dataPath + "!/assets";
- clientType = ClientType.Web;
- }
- else
- {
- _dataPath = "file://" + Application.dataPath + "/StreamingAssets"; ;
- clientType = ClientType.Desktop;
- }
- _dataPath = Application.streamingAssetsPath;
-
- }
- public int LagCount
- {
- get
- {
- return lagpoints.Count;
- }
- }
- int totallag
- {
- get
- {
- int q = 0;
- foreach (var g in lagpoints)
- {
- q += g;
- }
- return q;
- }
- }
- Queue<int> lagpoints = new Queue<int>();
- public int Averagelag
- {
- get
- {
- if (lagpoints.Count > 0)
- return totallag / lagpoints.Count;
- return 0;
- }
- }
- public void Myping(byte[] bytedata)
- {
- last_ping_time = timer;
- int lag = BitConverter.ToUInt16(bytedata, 1);
-
- this.lag = lag;
- if (lagpoints.Count > 5)
- lagpoints.Dequeue();
- lagpoints.Enqueue(lag);
- List<byte> list = new List<byte>();
- list.Add(30);
- list.Add(1);
- SendEnqueue(list.ToArray());
- }
- public void Disconnect(byte[] bytedata)
- {
- uint bid = BitConverter.ToUInt32(bytedata, 1);
- if (bid == account_id)
- Exit();
- else
- {
- print("disc id " + bid);
- }
- }
- public void Exit()
- {
- print("Client Exit");
- connected = false;
- login_sent = false;
- if (Mysocket != null)
- {
- Mysocket.Close();
- Mysocket = null;
- }
- connect_started = new DateTime();
- totalbytes = 0;
- account_id = 0;
- ACCOUNT_NAME = "";
- connected = false;
- sendDone = false;
- receiveDone = false;
- connectDone = false;
- StartConnectFlag = false;
- UnityEngine.SceneManagement.SceneManager.LoadScene(0);
- }
-
- public static void SendOneBytePacket(byte num)
- {
- SendOneByteParamPacket(num, 1);
- }
- public static void SendOneByteTwoParamsPacket(byte num, byte param1, byte param2)
- {
- byte[] data = { num, param1, param2 };
- SendEnqueue(data);
- }
- public static void SendThreeParamsIntPacket(byte num, int param1, int param2, int param3)
- {
- List<byte> list = new List<byte>();
- list.Add(num);
- list.AddRange(BitConverter.GetBytes(param1));
- list.AddRange(BitConverter.GetBytes(param2));
- list.AddRange(BitConverter.GetBytes(param3));
- SendEnqueue(list.ToArray());
- }
-
- public static void SendOneByteParamPacket(byte num, byte param)
- {
- byte[] data = { num, param };
- byteSend(data);
- }
-
- public static void SendTwoByteParamPacket(byte num, ushort param)
- {
- List<byte> list = new List<byte>();
- list.Add(num);
- list.AddRange(BitConverter.GetBytes(param));
- SendEnqueue(list.ToArray());
- }
-
- public static void SendFourByteParamPacket(byte num, uint param)
- {
- List<byte> list = new List<byte>();
- list.Add(num);
- list.AddRange(BitConverter.GetBytes(param));
- SendEnqueue(list.ToArray());
- }
- public static DateTime connect_started;
- public void Login(byte[] bytedata)
- {
- uint accid = BitConverter.ToUInt32(bytedata, 1);
- if (accid == 0xFFFFFFFF)
- {
- Debug.LogError("Login or password incorrect");
- AuthorizationController.error = true;
- return;
- }
- else if (accid == 0xFFFFFFFE)
- {
- Debug.LogError("Account was already connected");
- return;
- }
- else if (accid == 0xFFFFFFFD)
- {
- Debug.LogError("Incorrect client version");
- return;
- }
- company_id = BitConverter.ToUInt32(bytedata, 5);
- AuthorizationController.success = true;
- account_id = accid;
-
- }
- #region system functions
- public void Register(int packnum, OnReceive func)
- {
- packets[packnum] = func;
- }
- private void Register(int packnum, OnReceive func, int len)
- {
- packets[packnum] = func;
- if (len > 1)
- PacketLength[packnum] = len;
- }
- public int GetLength(byte[] data, int num, int offset)
- {
- int leng;
- if (!PacketLength.ContainsKey(num))
- {
- var rest = data.Length - offset;
-
- if (rest < 5)
- return 1;
- leng = BitConverter.ToInt32(data, offset + 1);
- }
- else
- leng = PacketLength[num];
- return leng;
- }
- int maximumPacketsPerUpdate = 50;
- public string tempflag;
- public static void printBytes(byte[] bytedata, bool sent = false)
- {
- var prefix = "";
- if (!sent)
- {
- if (!ShowPackets)
- return;
- }
- else
- {
- if (!ShowPacketsSent)
- return;
- prefix = "sent ";
- }
- byte[] newbuf = new byte[bytedata.Length];
- Array.Copy(bytedata, newbuf, bytedata.Length);
- string mygg = prefix + "printBytes: ";
- foreach (byte b in newbuf)
- {
- mygg += b + " ";
- }
- Debug.Log(newbuf.Length + " bytes: " + mygg);
- }
- public void Update()
- {
- #if UNITY_WEBGL
- Receive();
- #endif
- if (instance == null || !entered)
- {
- return;
- }
- else
- {
- if (!StartConnectFlag)
- {
- StartCoroutine(Connect());
- StartConnectFlag = true;
- }
- }
- int from_connect = DateTime.Now.Subtract(connect_started).Seconds;
- if (from_connect > 7 && from_connect != DateTime.Now.Second && account_id == 0)
- {
- Exit();
- }
- var processedCount = 0;
- while (PacketQueue.Count > 0 && processedCount < maximumPacketsPerUpdate)
- {
- byte[] packetbytes;
- lock (packetqueuelock)
- {
- packetbytes = PacketQueue.Dequeue();
- }
- int offset = 0;
- int totallen = 0;
- int num = packetbytes[0];
- int leng = GetLength(packetbytes, packetbytes[0], 0);
- if (leng <= packetbytes.Length)
- {
- while (offset < packetbytes.Length)
- {
- num = packetbytes[offset];
- leng = GetLength(packetbytes, num, offset);
- totallen += leng;
- print("num " + num + " leng " + leng);
- byte[] newpack = new byte[leng];
- Array.Copy(packetbytes, offset, newpack, 0, leng);
- offset += leng;
- printBytes(newpack);
- processedCount++;
- packets[num](newpack);
- }
- }
- }
- }
- public void Start()
- {
- tempflag = "";
- entered = true;
- }
- public void LateUpdate()
- {
- while (SendQueue.Count > 0)
- {
-
- byte[] sendstring = SendQueue.Dequeue();
-
- byteSend(sendstring);
- }
- }
- public class StateObject
- {
-
-
- public const int BufferSize = 128000;
-
- public byte[] buffer = new byte[BufferSize];
-
- }
- public static Queue<byte[]> PacketQueue = new Queue<byte[]>();
- static Queue<byte[]> SendQueue = new Queue<byte[]>();
- public static bool receiveDone, connectDone, sendDone = false;
- public static StateObject state = new StateObject();
- private IEnumerator Connect()
- {
- Debug.Log("Connect");
-
- #if UNITY_WEBGL
- var uristring = $"ws://{ServerName}:{webglPort}/ws";
- Debug.Log($"WebSocket tryconnect: {uristring}");
- WebSocket client = new WebSocket(new Uri(uristring));
- Mysocket = client;
- yield return StartCoroutine(Mysocket.Connect());
- connectDone = (Mysocket.error == null);
- if (!connectDone)
- {
- Debug.Log("WebSocket error: " + Mysocket.error);
- yield break;
- }
- #else
-
-
- new IPAddress(new byte[] { 127, 0, 0, 1 });
- IPHostEntry ipHostInfo = Dns.GetHostEntry(ServerName);
-
-
-
- IPAddress[] ipv4Addresses = Array.FindAll(ipHostInfo.AddressList, a => a.AddressFamily == AddressFamily.InterNetwork);
-
-
- IPAddress ipAddress = ipv4Addresses[0];
-
- IPEndPoint remoteEP = new IPEndPoint(ipAddress, socketPort);
-
- Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-
- print("remoteEP.AddressFamily " + AddressFamily.InterNetwork);
- print("client " + client.AddressFamily);
- Mysocket = client;
-
- try
- {
- client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
- }
- catch (Exception e)
- {
- print(e.Message);
- }
- int num = 0;
- while (!connectDone && num < 10)
- {
- num++;
- yield return new WaitForSeconds(0.2f);
- }
- if (!connectDone)
- {
- print(socketPort + " port failed");
- yield break;
- }
- #endif
- print("connected");
- connected = true;
- while (true)
- {
- if (!entered)
- break;
- while (!sendDone && connected)
- {
- yield return 1;
- }
- Receive();
- while (!receiveDone && connected)
- {
- yield return 1;
- }
- receiveDone = false;
- break;
- }
- yield break;
- }
- private static void ConnectCallback(IAsyncResult ar)
- {
-
- Socket client = (Socket)ar.AsyncState;
- connect_started = DateTime.Now;
-
- try
- {
- client.EndConnect(ar);
- }
- catch (Exception e)
- {
- print(e.Message);
- }
-
- connectDone = true;
- }
- private void Receive()
- {
- #if UNITY_WEBGL
- CheckWebSocket();
- if (Mysocket == null)
- return;
- byte[] packet = null;
- do
- {
- packet = Mysocket.Recv();
- if (packet != null)
- {
- lock (packetqueuelock)
- {
- PacketQueue.Enqueue(packet);
- }
- receiveDone = true;
- totalbytes += packet.Length;
- }
- }
- while (packet != null);
- #else
- Mysocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReceiveCallback), state);
- #endif
- }
- public static object packetqueuelock = new object();
- public static Queue<byte[]> tempqueue = new Queue<byte[]>();
- public bool CheckLength(byte[] packetbytes)
- {
- if (packetbytes.Length > 0)
- {
- int offset = 0;
-
- int num = packetbytes[0];
- int leng = GetLength(packetbytes, packetbytes[0], 0);
- if (leng <= packetbytes.Length)
- {
- while (offset < packetbytes.Length)
- {
- num = packetbytes[offset];
- leng = GetLength(packetbytes, num, offset);
- if (leng == 1)
- {
- print("Error: CheckLength: packet not complete");
- return false;
- }
-
- if (leng == 0)
- {
- print("CheckLength2 break! length error " + num);
- dc = true;
- break;
- }
- offset += leng;
- }
- }
- if (offset == packetbytes.Length)
- return true;
- return false;
- }
- return false;
- }
- public static int totalbytes = 0;
- #if !UNITY_WEBGL
- private void ReceiveCallback(IAsyncResult ar)
- {
-
-
- StateObject state = (StateObject)ar.AsyncState;
-
- int bytesRead = 0;
- bytesRead = Mysocket.EndReceive(ar);
- if (bytesRead > 0)
- {
-
- byte[] newbuf = new Byte[bytesRead];
- Array.Copy(state.buffer, newbuf, bytesRead);
-
-
-
-
-
-
-
-
-
-
-
-
-
- byte[] tocheck = newbuf;
- if (tempqueue.Count > 0)
- {
- Queue<byte[]> myqueue = new Queue<byte[]>(tempqueue);
- List<byte> list = new List<byte>();
- while (myqueue.Count > 0)
- {
- list.AddRange(myqueue.Dequeue());
- }
- list.AddRange(newbuf);
- tocheck = list.ToArray();
- }
- if (!CheckLength(tocheck))
- {
- tempqueue.Clear();
- tempqueue.Enqueue(tocheck);
- }
- else
- {
- tempqueue.Clear();
- lock (packetqueuelock)
- {
- PacketQueue.Enqueue(tocheck);
- }
- }
- receiveDone = true;
- Receive();
- }
- }
- #endif
- #if UNITY_WEBGL
- private static void CheckWebSocket()
- {
- if (Mysocket != null && Mysocket.error != null)
- {
- Debug.LogError(Mysocket.error);
- instance.Exit();
- }
- }
- #endif
- private static void byteSend(byte[] tosend)
- {
- if (tosend == null)
- {
- Debug.LogError("tosend null");
- return;
- }
- printBytes(tosend, true);
- #if UNITY_WEBGL
- byte[] webglbuf = new Byte[tosend.Length];
- Array.Copy(tosend, webglbuf, tosend.Length);
- CheckWebSocket();
- if (Mysocket != null)
- {
- Mysocket.Send(webglbuf);
- sendDone = true;
- Debug.Log("websocket sendDone");
- }
- #else
- try
- {
-
- Mysocket.BeginSend(tosend, 0, tosend.Length, 0, SendCallback, Mysocket);
- }
- catch (Exception e)
- {
- if (instance != null)
- {
- print(e.Message);
- instance.Exit();
- }
- }
- #endif
- }
- #if !UNITY_WEBGL
- private static void SendCallback(IAsyncResult ar)
- {
-
- Socket client = (Socket)ar.AsyncState;
-
-
- client.EndSend(ar);
-
-
- sendDone = true;
- }
- #endif
- #endregion
- public static string GetMD5Hash(string input)
- {
- System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
- byte[] bs = Encoding.UTF8.GetBytes(input);
- bs = x.ComputeHash(bs);
- StringBuilder s = new StringBuilder();
- foreach (byte b in bs)
- {
- s.Append(b.ToString("x2").ToLower());
- }
- string password = s.ToString();
- return password;
- }
-
-
-
- public void CoordinatesRequest(long timeStart, long timeEnd, byte resolution, uint locationID, uint account_id)
- {
- login_sent = true;
- Debug.Log("SendRequestCoordinates");
- List<byte> list = new List<byte>();
- list.Add(3);
- list.AddRange(BitConverter.GetBytes(account_id));
- list.AddRange(BitConverter.GetBytes(timeStart));
- list.AddRange(BitConverter.GetBytes(timeEnd));
- list.Add(resolution);
- list.AddRange(BitConverter.GetBytes(locationID));
- SendEnqueue(list.ToArray());
- }
- public void SendGetUsers()
- {
- SendGetUsers(instance.company_id);
- }
-
- public static void SendGetUsers(uint companyId)
- {
- List<byte> list = new List<byte>();
- list.Add(47);
- list.AddRange(BitConverter.GetBytes(companyId));
- SendEnqueue(list.ToArray());
- }
- public static byte[] ConstructVariablePacket(byte num, byte[] vardatabytes)
- {
- List<byte> bytedata = new List<byte>();
- bytedata.Add(num);
- int len = vardatabytes.Length + 5;
- bytedata.AddRange(BitConverter.GetBytes(len));
- bytedata.AddRange(vardatabytes);
- return bytedata.ToArray();
- }
- public void MessageReceiver(string data)
- {
- var expl = data.Split(' ');
- var accname = expl[0];
- account_id = Convert.ToUInt32(expl[1]);
- company_id = Convert.ToUInt32(expl[2]);
- AuthorizationController.success = true;
-
- tempflag = data+" "+ accname;
- }
- public void SendLogin(string login, string passwordToEdit)
- {
- if (!connected)
- {
-
-
- return;
- }
- if (!login_sent)
- {
- login_sent = true;
- string pass = GetMD5Hash(passwordToEdit);
- byte[] bpass = Encoding.UTF8.GetBytes(pass);
- byte[] blogin = Encoding.UTF8.GetBytes(login);
- List<byte> list = new List<byte>();
- byte loginFlag = 1;
- int leng = (bpass.Length + blogin.Length + 6);
- list.Add(2);
- list.AddRange(BitConverter.GetBytes(leng));
- list.Add(loginFlag);
- list.AddRange(bpass);
- list.AddRange(blogin);
- SendEnqueue(list.ToArray());
- }
- }
- #region test functions
- public void ImgReceive(byte[] bytedata)
- {
- var imglen = bytedata.Length - 5;
- print("ImgReceive " + imglen);
- byte[] rawdata = new byte[imglen];
- Array.Copy(bytedata, 5, rawdata, 0, imglen);
-
- Texture2D tex = new Texture2D(2, 2);
- tex.LoadImage(rawdata);
-
- var rawimg = GameObject.Find("RawImage");
- if (rawimg != null)
- {
- print("rawimg2 not null");
-
-
- rawimg.GetComponent<RawImage>().texture = tex;
-
-
- }
- }
- public void TestImageSend(Texture2D tex)
- {
- byte[] bdata = new byte[0];
- var data = ConstructVariablePacket(55, bdata);
- SendEnqueue(data);
- }
- public void OnGUI()
- {
-
-
- if (GUI.Button(new Rect(250, 280, 160, 64), "Hello from web page! "+ tempflag))
- {
- var rawimg = GameObject.Find("RawImage");
- if (rawimg != null)
- {
- print("rawimg not null");
- var testimg = (Texture2D)Resources.Load("Image/map1", typeof(Texture2D));
- TestImageSend(testimg);
-
- }
-
-
-
- }
-
- }
- #endregion
- }
|