IEnumerator WebSocketConnection() { currentTime = TIME_INTERVAL; summary = new SummarizedData(); WebSocket w = new WebSocket(new Uri("ws://" + ip + ":" + port)); webSocket = w; yield return(StartCoroutine(w.Connect())); Debug.Log("Start"); while (true) { yield return(new WaitForEndOfFrame()); // Send data to the server regularly if (currentTime <= 0) { // data = GetData(); // char[] textToSend = new char[buffer.Length]; // buffer.CopyTo(0, textToSend, 0, buffer.Length); // SendData(textToSend.ToString()); SendData(buffer); buffer = ""; // clear buffer currentTime = TIME_INTERVAL; } else { currentTime -= Time.deltaTime; } string reply = w.RecvString(); if (reply != null) { Debug.Log(reply); HandleCommand(reply); } if (w.error != null) { Debug.LogError("Error: " + w.error); // break; } if (GameManager.gameState == GameManager.GameState.FINISHED) { // Upload the summarized data, make sure it only send once if (!sendSummary) { SendData(w, summary); sendSummary = true; } // break; } yield return(0); } w.Close(); }
void SendData(WebSocket w, SummarizedData data) { data.timestamp = UnixTimeNow(); // Send JSON string w.SendString(JsonConvert.SerializeObject(data)); }