| 1 | /************************************************************************************ |
| 2 | Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. |
| 3 | |
| 4 | Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use |
| 5 | the Utilities SDK except in compliance with the License, which is provided at the time of installation |
| 6 | or download, or which otherwise accompanies this software in either electronic or hard copy form. |
| 7 | |
| 8 | You may obtain a copy of the License at |
| 9 | https://developer.oculus.com/licenses/utilities-1.31 |
| 10 | |
| 11 | Unless required by applicable law or agreed to in writing, the Utilities SDK distributed |
| 12 | under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
| 13 | ANY KIND, either express or implied. See the License for the specific language governing |
| 14 | permissions and limitations under the License. |
| 15 | ************************************************************************************/ |
| 16 | |
| 17 | using System; |
| 18 | using System.Collections; |
| 19 | using System.Collections.Generic; |
| 20 | using System.Net; |
| 21 | using System.Net.Sockets; |
| 22 | using System.Diagnostics; |
| 23 | using System.Runtime.InteropServices; |
| 24 | using System.Threading; |
| 25 | using UnityEngine; |
| 26 | |
| 27 | using Debug = UnityEngine.Debug; |
| 28 | |
| 29 | public class OVRNetwork |
| 30 | { |
| 31 | public const int MaxBufferLength = 65536; |
| 32 | public const int MaxPayloadLength = MaxBufferLength - FrameHeader.StructSize; |
| 33 | |
| 34 | public const uint FrameHeaderMagicIdentifier = 0x5283A76B; |
| 35 | |
| 36 | [StructLayout(LayoutKind.Sequential, Pack = 1)] |
| 37 | struct FrameHeader |
| 38 | { |
| 39 | public uint protocolIdentifier; |
| 40 | public int payloadType; |
| 41 | public int payloadLength; |
| 42 | |
| 43 | public const int StructSize = sizeof(uint) + sizeof(int) + sizeof(int); |
| 44 | |
| 45 | // endianness conversion is NOT handled since all our current mobile/PC devices are little-endian |
| 46 | public byte[] ToBytes() |
| 47 | { |
| 48 | int size = Marshal.SizeOf(this); |
| 49 | Trace.Assert(size == StructSize); |
| 50 | |
| 51 | byte[] arr = new byte[size]; |
| 52 | |
| 53 | IntPtr ptr = Marshal.AllocHGlobal(size); |
| 54 | Marshal.StructureToPtr(this, ptr, true); |
| 55 | Marshal.Copy(ptr, arr, 0, size); |
| 56 | Marshal.FreeHGlobal(ptr); |
| 57 | return arr; |
| 58 | } |
| 59 | |
| 60 | public static FrameHeader FromBytes(byte[] arr) |
| 61 | { |
| 62 | FrameHeader header = new FrameHeader(); |
| 63 | |
| 64 | int size = Marshal.SizeOf(header); |
| 65 | Trace.Assert(size == StructSize); |
| 66 | |
| 67 | IntPtr ptr = Marshal.AllocHGlobal(size); |
| 68 | |
| 69 | Marshal.Copy(arr, 0, ptr, size); |
| 70 | |
| 71 | header = (FrameHeader)Marshal.PtrToStructure(ptr, header.GetType()); |
| 72 | Marshal.FreeHGlobal(ptr); |
| 73 | |
| 74 | return header; |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | public class OVRNetworkTcpServer |
| 79 | { |
| 80 | public TcpListener tcpListener = null; |
| 81 | |
| 82 | private readonly object clientsLock = new object(); |
| 83 | public readonly List<TcpClient> clients = new List<TcpClient>(); |
| 84 | |
| 85 | public void StartListening(int listeningPort) |
| 86 | { |
| 87 | if (tcpListener != null) |
| 88 | { |
| 89 | Debug.LogWarning("[OVRNetworkTcpServer] tcpListener is not null"); |
| 90 | return; |
| 91 | } |
| 92 | |
| 93 | IPAddress localAddr = IPAddress.Any; |
| 94 | |
| 95 | tcpListener = new TcpListener(localAddr, listeningPort); |
| 96 | try |
| 97 | { |
| 98 | tcpListener.Start(); |
| 99 | Debug.LogFormat("TcpListener started. Local endpoint: {0}", tcpListener.LocalEndpoint.ToString()); |
| 100 | } |
| 101 | catch (SocketException e) |
| 102 | { |
| 103 | Debug.LogWarningFormat("[OVRNetworkTcpServer] Unsable to start TcpListener. Socket exception: {0}", e.Message); |
| 104 | Debug.LogWarning("It could be caused by multiple instances listening at the same port, or the port is forwarded to the Android device through ADB"); |
| 105 | Debug.LogWarning("If the port is forwarded through ADB, use the Android Tools in Tools/Oculus/System Metrics Profiler to kill the server"); |
| 106 | tcpListener = null; |
| 107 | } |
| 108 | |
| 109 | if (tcpListener != null) |
| 110 | { |
| 111 | Debug.LogFormat("[OVRNetworkTcpServer] Start Listening on port {0}", listeningPort); |
| 112 | |
| 113 | try |
| 114 | { |
| 115 | tcpListener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), tcpListener); |
| 116 | } |
| 117 | catch (Exception e) |
| 118 | { |
| 119 | Debug.LogWarningFormat("[OVRNetworkTcpServer] can't accept new client: {0}", e.Message); |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | public void StopListening() |
| 125 | { |
| 126 | if (tcpListener == null) |
| 127 | { |
| 128 | Debug.LogWarning("[OVRNetworkTcpServer] tcpListener is null"); |
| 129 | return; |
| 130 | } |
| 131 | |
| 132 | lock (clientsLock) |
| 133 | { |
| 134 | clients.Clear(); |
| 135 | } |
| 136 | tcpListener.Stop(); |
| 137 | tcpListener = null; |
| 138 | |
| 139 | Debug.Log("[OVRNetworkTcpServer] Stopped listening"); |
| 140 | } |
| 141 | |
| 142 | private void DoAcceptTcpClientCallback(IAsyncResult ar) |
| 143 | { |
| 144 | TcpListener listener = ar.AsyncState as TcpListener; |
| 145 | try |
| 146 | { |
| 147 | TcpClient client = listener.EndAcceptTcpClient(ar); |
| 148 | lock (clientsLock) |
| 149 | { |
| 150 | clients.Add(client); |
| 151 | Debug.Log("[OVRNetworkTcpServer] client added"); |
| 152 | } |
| 153 | |
| 154 | try |
| 155 | { |
| 156 | tcpListener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), tcpListener); |
| 157 | } |
| 158 | catch (Exception e) |
| 159 | { |
| 160 | Debug.LogWarningFormat("[OVRNetworkTcpServer] can't accept new client: {0}", e.Message); |
| 161 | } |
| 162 | } |
| 163 | catch (ObjectDisposedException) |
| 164 | { |
| 165 | // Do nothing. It happens when stop preview in editor, which is normal behavior. |
| 166 | } |
| 167 | catch (Exception e) |
| 168 | { |
| 169 | Debug.LogWarningFormat("[OVRNetworkTcpServer] EndAcceptTcpClient failed: {0}", e.Message); |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | public bool HasConnectedClient() |
| 174 | { |
| 175 | lock (clientsLock) |
| 176 | { |
| 177 | foreach (TcpClient client in clients) |
| 178 | { |
| 179 | if (client.Connected) |
| 180 | { |
| 181 | return true; |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | return false; |
| 186 | } |
| 187 | |
| 188 | public void Broadcast(int payloadType, byte[] payload) |
| 189 | { |
| 190 | if (payload.Length > OVRNetwork.MaxPayloadLength) |
| 191 | { |
| 192 | Debug.LogWarningFormat("[OVRNetworkTcpServer] drop payload because it's too long: {0} bytes", payload.Length); |
| 193 | } |
| 194 | |
| 195 | FrameHeader header = new FrameHeader(); |
| 196 | header.protocolIdentifier = FrameHeaderMagicIdentifier; |
| 197 | header.payloadType = payloadType; |
| 198 | header.payloadLength = payload.Length; |
| 199 | |
| 200 | byte[] headerBuffer = header.ToBytes(); |
| 201 | |
| 202 | byte[] dataBuffer = new byte[headerBuffer.Length + payload.Length]; |
| 203 | headerBuffer.CopyTo(dataBuffer, 0); |
| 204 | payload.CopyTo(dataBuffer, headerBuffer.Length); |
| 205 | |
| 206 | lock (clientsLock) |
| 207 | { |
| 208 | foreach (TcpClient client in clients) |
| 209 | { |
| 210 | if (client.Connected) |
| 211 | { |
| 212 | try |
| 213 | { |
| 214 | client.GetStream().BeginWrite(dataBuffer, 0, dataBuffer.Length, new AsyncCallback(DoWriteDataCallback), client.GetStream()); |
| 215 | } |
| 216 | catch (SocketException e) |
| 217 | { |
| 218 | Debug.LogWarningFormat("[OVRNetworkTcpServer] close client because of socket error: {0}", e.Message); |
| 219 | client.GetStream().Close(); |
| 220 | client.Close(); |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | private void DoWriteDataCallback(IAsyncResult ar) |
| 228 | { |
| 229 | NetworkStream stream = ar.AsyncState as NetworkStream; |
| 230 | stream.EndWrite(ar); |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | public class OVRNetworkTcpClient |
| 235 | { |
| 236 | public Action connectionStateChangedCallback; |
| 237 | public Action<int, byte[], int, int> payloadReceivedCallback; |
| 238 | |
| 239 | public enum ConnectionState |
| 240 | { |
| 241 | Disconnected, |
| 242 | Connected, |
| 243 | Connecting |
| 244 | } |
| 245 | |
| 246 | public ConnectionState connectionState |
| 247 | { |
| 248 | get |
| 249 | { |
| 250 | if (tcpClient == null) |
| 251 | { |
| 252 | return ConnectionState.Disconnected; |
| 253 | } |
| 254 | else |
| 255 | { |
| 256 | if (tcpClient.Connected) |
| 257 | { |
| 258 | return ConnectionState.Connected; |
| 259 | } |
| 260 | else |
| 261 | { |
| 262 | return ConnectionState.Connecting; |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | public bool Connected |
| 269 | { |
| 270 | get |
| 271 | { |
| 272 | return connectionState == ConnectionState.Connected; |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | TcpClient tcpClient = null; |
| 277 | |
| 278 | byte[][] receivedBuffers = { new byte[OVRNetwork.MaxBufferLength], new byte[OVRNetwork.MaxBufferLength] }; |
| 279 | int receivedBufferIndex = 0; |
| 280 | int receivedBufferDataSize = 0; |
| 281 | ManualResetEvent readyReceiveDataEvent = new ManualResetEvent(true); |
| 282 | |
| 283 | public void Connect(int listeningPort) |
| 284 | { |
| 285 | if (tcpClient == null) |
| 286 | { |
| 287 | receivedBufferIndex = 0; |
| 288 | receivedBufferDataSize = 0; |
| 289 | readyReceiveDataEvent.Set(); |
| 290 | |
| 291 | string remoteAddress = "127.0.0.1"; |
| 292 | tcpClient = new TcpClient(AddressFamily.InterNetwork); |
| 293 | tcpClient.BeginConnect(remoteAddress, listeningPort, new AsyncCallback(ConnectCallback), tcpClient); |
| 294 | |
| 295 | if (connectionStateChangedCallback != null) |
| 296 | { |
| 297 | connectionStateChangedCallback(); |
| 298 | } |
| 299 | } |
| 300 | else |
| 301 | { |
| 302 | Debug.LogWarning("[OVRNetworkTcpClient] already connected"); |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | void ConnectCallback(IAsyncResult ar) |
| 307 | { |
| 308 | try |
| 309 | { |
| 310 | TcpClient client = ar.AsyncState as TcpClient; |
| 311 | client.EndConnect(ar); |
| 312 | Debug.LogFormat("[OVRNetworkTcpClient] connected to {0}", client.ToString()); |
| 313 | } |
| 314 | catch (Exception e) |
| 315 | { |
| 316 | Debug.LogWarningFormat("[OVRNetworkTcpClient] connect error {0}", e.Message); |
| 317 | } |
| 318 | |
| 319 | if (connectionStateChangedCallback != null) |
| 320 | { |
| 321 | connectionStateChangedCallback(); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | public void Disconnect() |
| 326 | { |
| 327 | if (tcpClient != null) |
| 328 | { |
| 329 | if (!readyReceiveDataEvent.WaitOne(5)) |
| 330 | { |
| 331 | Debug.LogWarning("[OVRNetworkTcpClient] readyReceiveDataEvent not signaled. data receiving timeout?"); |
| 332 | } |
| 333 | |
| 334 | Debug.Log("[OVRNetworkTcpClient] close tcpClient"); |
| 335 | try |
| 336 | { |
| 337 | tcpClient.GetStream().Close(); |
| 338 | tcpClient.Close(); |
| 339 | } |
| 340 | catch (Exception e) |
| 341 | { |
| 342 | Debug.LogWarning("[OVRNetworkTcpClient] " + e.Message); |
| 343 | } |
| 344 | tcpClient = null; |
| 345 | |
| 346 | if (connectionStateChangedCallback != null) |
| 347 | { |
| 348 | connectionStateChangedCallback(); |
| 349 | } |
| 350 | } |
| 351 | else |
| 352 | { |
| 353 | Debug.LogWarning("[OVRNetworkTcpClient] not connected"); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | public void Tick() |
| 358 | { |
| 359 | if (tcpClient == null || !tcpClient.Connected) |
| 360 | { |
| 361 | return; |
| 362 | } |
| 363 | |
| 364 | if (readyReceiveDataEvent.WaitOne(TimeSpan.Zero)) |
| 365 | { |
| 366 | if (tcpClient.GetStream().DataAvailable) |
| 367 | { |
| 368 | if (receivedBufferDataSize >= OVRNetwork.MaxBufferLength) |
| 369 | { |
| 370 | Debug.LogWarning("[OVRNetworkTcpClient] receive buffer overflow. It should not happen since we have the constraint on message size"); |
| 371 | Disconnect(); |
| 372 | return; |
| 373 | } |
| 374 | |
| 375 | readyReceiveDataEvent.Reset(); |
| 376 | int maximumDataSize = OVRSystemPerfMetrics.MaxBufferLength - receivedBufferDataSize; |
| 377 | |
| 378 | tcpClient.GetStream().BeginRead(receivedBuffers[receivedBufferIndex], receivedBufferDataSize, maximumDataSize, new AsyncCallback(OnReadDataCallback), tcpClient.GetStream()); |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | void OnReadDataCallback(IAsyncResult ar) |
| 384 | { |
| 385 | NetworkStream stream = ar.AsyncState as NetworkStream; |
| 386 | try |
| 387 | { |
| 388 | int numBytes = stream.EndRead(ar); |
| 389 | receivedBufferDataSize += numBytes; |
| 390 | |
| 391 | while (receivedBufferDataSize >= FrameHeader.StructSize) |
| 392 | { |
| 393 | FrameHeader header = FrameHeader.FromBytes(receivedBuffers[receivedBufferIndex]); |
| 394 | if (header.protocolIdentifier != OVRNetwork.FrameHeaderMagicIdentifier) |
| 395 | { |
| 396 | Debug.LogWarning("[OVRNetworkTcpClient] header mismatch"); |
| 397 | Disconnect(); |
| 398 | return; |
| 399 | } |
| 400 | |
| 401 | if (header.payloadLength < 0 || header.payloadLength > OVRNetwork.MaxPayloadLength) |
| 402 | { |
| 403 | Debug.LogWarningFormat("[OVRNetworkTcpClient] Sanity check failed. PayloadLength %d", header.payloadLength); |
| 404 | Disconnect(); |
| 405 | return; |
| 406 | } |
| 407 | |
| 408 | if (receivedBufferDataSize >= FrameHeader.StructSize + header.payloadLength) |
| 409 | { |
| 410 | if (payloadReceivedCallback != null) |
| 411 | { |
| 412 | payloadReceivedCallback(header.payloadType, receivedBuffers[receivedBufferIndex], FrameHeader.StructSize, header.payloadLength); |
| 413 | } |
| 414 | |
| 415 | // swap receive buffer |
| 416 | int newBufferIndex = 1 - receivedBufferIndex; |
| 417 | int newBufferDataSize = receivedBufferDataSize - (FrameHeader.StructSize + header.payloadLength); |
| 418 | if (newBufferDataSize > 0) |
| 419 | { |
| 420 | Array.Copy(receivedBuffers[receivedBufferIndex], (FrameHeader.StructSize + header.payloadLength), receivedBuffers[newBufferIndex], 0, newBufferDataSize); |
| 421 | } |
| 422 | receivedBufferIndex = newBufferIndex; |
| 423 | receivedBufferDataSize = newBufferDataSize; |
| 424 | } |
| 425 | } |
| 426 | readyReceiveDataEvent.Set(); |
| 427 | } |
| 428 | catch (SocketException e) |
| 429 | { |
| 430 | Debug.LogErrorFormat("[OVRNetworkTcpClient] OnReadDataCallback: socket error: {0}", e.Message); |
| 431 | Disconnect(); |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | } |