5 using System.Collections.Generic;
8 #if !UNITY_EDITOR && UNITY_WSA && !(ENABLE_IL2CPP && NET_STANDARD_2_0) 9 using Windows.Networking.Sockets;
10 using Windows.Storage.Streams;
11 using Windows.Networking;
12 using Windows.Foundation;
13 using System.Threading.Tasks;
23 [Tooltip(
"The connection port on the machine to use.")]
24 public int SendConnectionPort = 11000;
30 public delegate
void OnDataReady(byte[] data);
32 #if UNITY_WSA && !(ENABLE_IL2CPP && NET_STANDARD_2_0) 33 public event OnDataReady DataReadyEvent;
39 private string serverIp;
44 private bool waitingForConnection =
false;
49 private byte[] mostRecentDataBuffer;
51 #if !UNITY_EDITOR && UNITY_WSA && !(ENABLE_IL2CPP && NET_STANDARD_2_0) 52 private StreamSocket networkConnection;
60 private StreamSocketListener networkListener;
65 private float timeToDeferFailedConnections = 10.0f;
74 mostRecentDataBuffer = data;
83 serverIp = newServerIp.Trim();
92 return ConnectListener();
95 private Queue<Action> DeferredActionQueue =
new Queue<Action>();
99 lock (DeferredActionQueue)
101 while (DeferredActionQueue.Count > 0)
103 DeferredActionQueue.Dequeue()();
109 #if !UNITY_EDITOR && UNITY_WSA && !(ENABLE_IL2CPP && NET_STANDARD_2_0) 110 private void RequestDataRetry()
112 if (!RequestAndGetData())
114 Invoke(
"RequestDataRetry", timeToDeferFailedConnections);
124 #if !UNITY_EDITOR && UNITY_WSA && !(ENABLE_IL2CPP && NET_STANDARD_2_0) 125 Task t =
new Task(() =>
127 networkListener =
new StreamSocketListener();
128 networkListener.ConnectionReceived += NetworkListener_ConnectionReceived;
129 networkListener.BindServiceNameAsync(SendConnectionPort.ToString()).GetResults();
134 Debug.Log(
"This script is not intended to be run from the Unity Editor");
136 Debug.Log(
string.Format(
"serverIP = {0} waitingForConnection = {1} mostRecentDataBuffer = {2}", serverIp, waitingForConnection, mostRecentDataBuffer == null ?
"No there" :
"there"));
143 private bool ConnectListener()
145 #if !UNITY_EDITOR && UNITY_WSA && !(ENABLE_IL2CPP && NET_STANDARD_2_0) 146 if (waitingForConnection)
148 Debug.Log(
"Not a good time to connect listener");
152 waitingForConnection =
true;
153 Debug.Log(
"Connecting to " + serverIp);
154 HostName networkHost =
new HostName(serverIp);
155 networkConnection =
new StreamSocket();
157 IAsyncAction outstandingAction = networkConnection.ConnectAsync(networkHost, SendConnectionPort.ToString());
158 AsyncActionCompletedHandler aach =
new AsyncActionCompletedHandler(RcvNetworkConnectedHandler);
159 outstandingAction.Completed = aach;
167 #if !UNITY_EDITOR && UNITY_WSA && !(ENABLE_IL2CPP && NET_STANDARD_2_0) 168 private void NetworkListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
177 if (mostRecentDataBuffer != null)
179 IOutputStream stream = args.Socket.OutputStream;
180 using (DataWriter writer =
new DataWriter(stream))
182 writer.WriteInt32(mostRecentDataBuffer.Length);
183 writer.WriteBytes(mostRecentDataBuffer);
184 writer.StoreAsync().AsTask().Wait();
185 writer.FlushAsync().AsTask().Wait();
190 Debug.LogError(
"No data to send but we've been connected to. This is unexpected.");
199 private async
void RcvNetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status)
202 if (status == AsyncStatus.Completed)
204 DataReader networkDataReader;
207 using (networkDataReader =
new DataReader(networkConnection.InputStream))
210 DataReaderLoadOperation drlo = networkDataReader.LoadAsync(4);
211 while (drlo.Status == AsyncStatus.Started)
216 int dataSize = networkDataReader.ReadInt32();
219 Debug.Log(
"Super bad super big data size");
223 mostRecentDataBuffer =
new byte[dataSize];
226 await networkDataReader.LoadAsync((uint)dataSize);
227 networkDataReader.ReadBytes(mostRecentDataBuffer);
230 DataReadyEvent?.Invoke(mostRecentDataBuffer);
235 Debug.Log(
"Failed to establish connection for rcv. Error Code: " + asyncInfo.ErrorCode);
241 DeferredActionQueue.Enqueue(() =>
243 Invoke(
"RequestDataRetry", timeToDeferFailedConnections);
247 networkConnection.Dispose();
248 waitingForConnection =
false;