Tanoda
WebSocketDemo.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Text;
5using GILES;
6using UnityEngine;
7
8// Use plugin namespace
10using NaughtyAttributes;
11#if TRILIB_2
12using TriLibCore.Utils;
13using TriLibCore.General;
14#else
15using TriLib;
16#endif
17
18public class WebSocketDemo : pb_MonoBehaviourSingleton<WebSocketDemo>
19{
20 public string hostIP = "127.0.0.1";
21 public ushort Port = 5656;
22 private WebSocket ws;
23 [SerializeField]private float lastMessage = 0.0f;
24 public List<GameObject> syncObjects = new List<GameObject>();
25 private byte[] sendByteArray = new byte[4096];
26 private readonly object lockobject = new object();
27
28 // Use this for initialization
29 void Start () {
30
31 Dispatcher.CheckInstance();
32 // Create WebSocket instance
33 ws = WebSocketFactory.CreateInstance($"ws://{hostIP}:{Port}/sync");
34
35 // Add OnOpen event listener
36 ws.OnOpen += () =>
37 {
38 Debug.Log("WS connected!");
39 Debug.Log("WS state: " + ws.GetState().ToString());
40 Dispatcher.InvokeAsync(
41#if TRILIB_2
42 new ContextualizedAction(
43#endif
44 () =>
45 {
46 lastMessage = Time.time;
47 LoadingManager.instance.HideWindow();
48 CreateSendPacket();
49 ws.Send(sendByteArray);
50 }
51#if TRILIB_2
52 )
53#endif
54 );
55 };
56 // Add OnMessage event listener
57 ws.OnMessage += (byte[] msg) =>
58 {
59 Debug.Log("WS client received message: " + Encoding.UTF8.GetString(msg));
60
61 Dispatcher.InvokeAsync(
62#if TRILIB_2
63 new ContextualizedAction(
64#endif
65 () =>
66 {
67 lastMessage = Time.time;
68 CreateSendPacket();
69 ws.Send(sendByteArray);
70 }
71#if TRILIB_2
72 )
73#endif
74 );
75 };
76
77 // Add OnError event listener
78 ws.OnError += (string errMsg) =>
79 {
80 Debug.Log("WS error: " + errMsg);
81 };
82
83 // Add OnClose event listener
84 ws.OnClose += (WebSocketCloseCode code) =>
85 {
86 Debug.Log("WS closed with code: " + code.ToString());
87 if (code != WebSocketCloseCode.Normal)
88 {
89 Dispatcher.InvokeAsync(
90#if TRILIB_2
91 new ContextualizedAction(
92#endif
93 () =>
94 {
95 //LoadingManager.instance.HideWindow();
96 //PopupManager.instance.ShowPopup("Error",
97 // "Connection closed with error code: 0x" + code.ToString("X") +
98 // "\r\nRealtime interactions will be disabled!");
99 //enabled = false;
100 })
101#if TRILIB_2
102 )
103#endif
104
105 ;
106 }
107 };
108
109 // Connect to the server
110 ws.Connect();
111
112 }
113
114 private void OnDestroy()
115 {
116 ws.Close();
117 }
118
119 [Button]
120 public void FillSyncList()
121 {
122 lock (lockobject)
123 {
124 syncObjects.Clear();
125 var allsyncedobjects = FindObjectsOfType<SyncThis>();
126 foreach (var syncedobject in allsyncedobjects)
127 {
128 syncObjects.Add(syncedobject.gameObject);
129 }
130 }
131 }
132
133 [Button]
134 public void ClearSyncList()
135 {
136 lock (lockobject)
137 {
138 syncObjects.Clear();
139 }
140 }
141
142 private void FixedUpdate()
143 {
144 if (lastMessage + 3.0f < Time.time && ws.GetState() == WebSocketState.Open)
145 {
146
147 lock (lockobject)
148 {
149 CreateSendPacket();
150 ws.Send(sendByteArray);
151 }
152 }
153
154 //if (lastMessage == 0.0f && ws.GetState() == WebSocketState.Connecting && Time.time > 10.0f) //timeout
155 //{
156 //ws.Close();
157 //LoadingManager.instance.HideWindow();
158 //PopupManager.instance.ShowPopup("Error",
159 // "Connection timed out!\r\nRealtime interactions will be disabled!");
160 //enabled = false;
161 //}
162 }
163
164 private void CreateSendPacket()
165 {
166 int offset = 0;
167 foreach (var go in syncObjects)
168 {
169
170 sendByteArray[offset] = (byte) go.name.Length;
171 offset++;
172 foreach (var c in go.name)
173 {
174 sendByteArray[offset] = (byte)c;
175 offset++;
176 }
177
178 CopyVector3ToByteArray(ref sendByteArray, ref offset, go.transform.localPosition);
179 CopyVector3ToByteArray(ref sendByteArray, ref offset, go.transform.localEulerAngles);
180
181 #region BiztosLehetneSzebben
182
183 //var temp = BitConverter.GetBytes(go.transform.localPosition.x);
184 //foreach (var b in temp)
185 //{
186 // sendByteArray[offset] = b;
187 // offset++;
188 //}
189 //temp = BitConverter.GetBytes(go.transform.localPosition.y);
190 //foreach (var b in temp)
191 //{
192 // sendByteArray[offset] = b;
193 // offset++;
194 //}
195 //temp = BitConverter.GetBytes(go.transform.localPosition.z);
196 //foreach (var b in temp)
197 //{
198 // sendByteArray[offset] = b;
199 // offset++;
200 //}
201 //temp = BitConverter.GetBytes(go.transform.localEulerAngles.x);
202 //foreach (var b in temp)
203 //{
204 // sendByteArray[offset] = b;
205 // offset++;
206 //}
207 //temp = BitConverter.GetBytes(go.transform.localEulerAngles.y);
208 //foreach (var b in temp)
209 //{
210 // sendByteArray[offset] = b;
211 // offset++;
212 //}
213 //temp = BitConverter.GetBytes(go.transform.localEulerAngles.z);
214 //foreach (var b in temp)
215 //{
216 // sendByteArray[offset] = b;
217 // offset++;
218 //}
219 #endregion
220 }
221 }
222
223 private void CopyVector3ToByteArray(ref byte[] array, ref int arrayOffset, Vector3 value)
224 {
225 Buffer.BlockCopy( BitConverter.GetBytes( value.x ), 0, array, arrayOffset , 4 );
226 Buffer.BlockCopy( BitConverter.GetBytes( value.y ), 0, array, arrayOffset + 4, 4 );
227 Buffer.BlockCopy( BitConverter.GetBytes( value.z ), 0, array, arrayOffset + 8, 4 );
228 arrayOffset += 12;
229 }
230
231#if UNITY_EDITOR
232 [Button()]
233 void SendDummyText()
234 {
235 if (ws.GetState() == WebSocketState.Open)
236 {
237 ws.Send("dummy thicc");
238 }
239 }
240 [Button()]
241 void SendPing()
242 {
243 if (ws.GetState() == WebSocketState.Open)
244 {
245 Debug.Log("got pong: " + ws.Ping());
246 }
247 }
248#endif
249}
UnityEngine.UI.Button Button
Definition: Pointer.cs:7
UnityEngine.Debug Debug
Definition: TanodaServer.cs:19
void Send(byte[] data)
Send binary data over the socket.
Definition: WebSocket.cs:580
WebSocketMessageEventHandler OnMessage
Occurs when a message is received.
Definition: WebSocket.cs:454
WebSocketErrorEventHandler OnError
Occurs when an error was reported from WebSocket.
Definition: WebSocket.cs:459
WebSocketOpenEventHandler OnOpen
Occurs when the connection is opened.
Definition: WebSocket.cs:449
bool Ping()
Trys to ping the host.
Definition: WebSocket.cs:623
void Connect()
Open WebSocket connection
Definition: WebSocket.cs:532
void Close(WebSocketCloseCode code=WebSocketCloseCode.Normal, string reason=null)
Close WebSocket connection with optional status code and reason.
Definition: WebSocket.cs:555
WebSocketCloseEventHandler OnClose
Occurs when the socked was closed.
Definition: WebSocket.cs:464
WebSocketState GetState()
Return WebSocket connection state.
Definition: WebSocket.cs:644
void FillSyncList()
void ClearSyncList()
List< GameObject > syncObjects
WebSocketCloseCode
Web socket close codes.
Definition: WebSocket.cs:54
WebSocketState
Enum representing WebSocket connection state
Definition: WebSocket.cs:43