| | 1 | | using System; |
| | 2 | | using DCL.Interface; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using System.Net; |
| | 5 | | using System.Net.NetworkInformation; |
| | 6 | | using System.Threading; |
| | 7 | | using DCL; |
| | 8 | | using UnityEditor; |
| | 9 | | using UnityEngine; |
| | 10 | | using WebSocketSharp; |
| | 11 | | using WebSocketSharp.Server; |
| | 12 | |
|
| | 13 | | public class DCLWebSocketService : WebSocketBehavior |
| | 14 | | { |
| | 15 | | public static bool VERBOSE = false; |
| | 16 | |
|
| | 17 | | private void SendMessageToWeb(string type, string message) |
| | 18 | | { |
| | 19 | | #if (UNITY_EDITOR || UNITY_STANDALONE) |
| 0 | 20 | | var x = new Message() |
| | 21 | | { |
| | 22 | | type = type, |
| | 23 | | payload = message |
| | 24 | | }; |
| | 25 | |
|
| 0 | 26 | | if (ConnectionState == WebSocketState.Open) |
| | 27 | | { |
| 0 | 28 | | Send(Newtonsoft.Json.JsonConvert.SerializeObject(x)); |
| | 29 | |
|
| 0 | 30 | | if (VERBOSE) |
| | 31 | | { |
| 0 | 32 | | Debug.Log("SendMessageToWeb: " + type); |
| | 33 | | } |
| | 34 | | } |
| | 35 | | #endif |
| 0 | 36 | | } |
| | 37 | |
|
| | 38 | | public class Message |
| | 39 | | { |
| | 40 | | public string type; |
| | 41 | | public string payload; |
| | 42 | |
|
| 0 | 43 | | public override string ToString() { return string.Format("type = {0}... payload = {1}...", type, payload); } |
| | 44 | | } |
| | 45 | |
|
| | 46 | | protected override void OnMessage(MessageEventArgs e) |
| | 47 | | { |
| 0 | 48 | | base.OnMessage(e); |
| | 49 | |
|
| 0 | 50 | | lock (WebSocketCommunication.queuedMessages) |
| | 51 | | { |
| 0 | 52 | | Message finalMessage = JsonUtility.FromJson<Message>(e.Data); |
| | 53 | |
|
| 0 | 54 | | WebSocketCommunication.queuedMessages.Enqueue(finalMessage); |
| 0 | 55 | | WebSocketCommunication.queuedMessagesDirty = true; |
| 0 | 56 | | } |
| 0 | 57 | | } |
| | 58 | |
|
| | 59 | | protected override void OnError(ErrorEventArgs e) |
| | 60 | | { |
| 0 | 61 | | Debug.LogError(e.Message); |
| 0 | 62 | | base.OnError(e); |
| 0 | 63 | | } |
| | 64 | |
|
| | 65 | | protected override void OnClose(CloseEventArgs e) |
| | 66 | | { |
| 0 | 67 | | base.OnClose(e); |
| 0 | 68 | | WebInterface.OnMessageFromEngine -= SendMessageToWeb; |
| 0 | 69 | | DataStore.i.wsCommunication.communicationEstablished.Set(false); |
| 0 | 70 | | } |
| | 71 | |
|
| | 72 | | protected override void OnOpen() |
| | 73 | | { |
| 0 | 74 | | Debug.Log("WebSocket Communication Established"); |
| 0 | 75 | | base.OnOpen(); |
| | 76 | |
|
| 0 | 77 | | WebInterface.OnMessageFromEngine += SendMessageToWeb; |
| 0 | 78 | | DataStore.i.wsCommunication.communicationEstablished.Set(true); |
| 0 | 79 | | } |
| | 80 | | } |