// 対象のAction<T>をUniTask<T>に変換する
        public UniTask <T> ToUniTask <T>(MyClass <T> myClass)
        {
            var autoResetUtc = AutoResetUniTaskCompletionSource <T> .Create();

            myClass.onResult += value => autoResetUtc.TrySetResult(value);
            return(autoResetUtc.Task);
        }
Esempio n. 2
0
        public async UniTask Listen(int port)
        {
            try
            {
                listener = TcpListener.Create(port);
                listener.Start();

                listenCompletion = AutoResetUniTaskCompletionSource.Create();
                var acceptThread = new Thread(AcceptLoop)
                {
                    IsBackground = true
                };
                acceptThread.Start();

                Started.Invoke();

                await listenCompletion.Task;

                await UniTask.SwitchToMainThread();
            }
            finally
            {
                listener?.Stop();
            }
        }
Esempio n. 3
0
        /// <summary>
        ///     Start listening for incoming connection attempts.
        /// </summary>
        /// <returns>Returns completed if started up correctly.</returns>
        public override UniTask ListenAsync()
        {
            try
            {
                if (!_enetInitialized)
                {
                    if (InitializeEnet())
                    {
                        Debug.Log("Ignorance successfully initialized ENET.");
                        _enetInitialized = true;
                    }
                    else
                    {
                        Debug.LogError("Ignorance failed to initialize ENET! Cannot continue.");
                        return(UniTask.CompletedTask);
                    }
                }

                _server = new IgnoranceServer(Config, this);

                // start server up and listen for connections
                _server.Start();

                _listenCompletionSource = AutoResetUniTaskCompletionSource.Create();

                return(_listenCompletionSource.Task);
            }
            catch (Exception ex)
            {
                return(UniTask.FromException(ex));
            }
        }
Esempio n. 4
0
 private async UniTask WaitForMessages()
 {
     while (kcp.PeekSize() < 0 && unreliable.PeekSize() < 0 && open)
     {
         isWaiting     = true;
         dataAvailable = AutoResetUniTaskCompletionSource.Create();
         await dataAvailable.Task;
         isWaiting = false;
     }
 }
Esempio n. 5
0
        public UniTask WaitUntilCloseClick()
        {
            if (!_gameObject.activeSelf)
            {
                return(UniTask.CompletedTask);
            }

            var tcs = AutoResetUniTaskCompletionSource.Create();

            _waitForClose.Enqueue(tcs);
            return(tcs.Task);
        }
        public static UniTask <T> WaitForSignal <T>(this SignalBus signalBus)
        {
            var source = AutoResetUniTaskCompletionSource <T> .Create();

            signalBus.Subscribe <T>(Received);
            return(source.Task);

            void Received(T t)
            {
                signalBus.Unsubscribe <T>(Received);
                source.TrySetResult(t);
            }
        }
Esempio n. 7
0
        /// <summary>
        ///     Open up the port and listen for connections
        ///     Use in servers.
        /// </summary>
        /// <exception>If we cannot start the transport</exception>
        /// <returns></returns>
        public override UniTask ListenAsync()
        {
            if (_server != null)
            {
                Disconnect();
                _server = null;
            }

            _server = new Server(Port, this);

            _listenCompletionSource = AutoResetUniTaskCompletionSource.Create();

            return(_listenCompletionSource.Task);
        }
        /// <summary>
        ///     reads a message from connection
        /// </summary>
        /// <param name="buffer">buffer where the message will be written</param>
        /// <returns>true if we got a message, false if we got disconnected</returns>
        public async UniTask <byte> ReceiveAsync(MemoryStream buffer)
        {
            while (kcp.PeekSize() < 0 && unreliable.PeekSize() < 0 && open)
            {
                isWaiting     = true;
                dataAvailable = AutoResetUniTaskCompletionSource.Create();
                await dataAvailable.Task;
                isWaiting = false;
            }

            if (!open)
            {
                Disconnected?.Invoke();
                throw new EndOfStreamException();
            }

            if (unreliable.PeekSize() >= 0)
            {
                // we got a message in the unreliable channel
                int msgSize = unreliable.PeekSize();
                buffer.SetLength(msgSize);
                unreliable.Receive(buffer.GetBuffer(), (int)buffer.Length);
                buffer.Position = msgSize;
                return((byte)Channels.Unreliable);
            }
            else
            {
                int msgSize = kcp.PeekSize();
                // we have some data,  return it
                buffer.SetLength(msgSize);
                kcp.Receive(buffer.GetBuffer());
                buffer.Position = msgSize;

                // if we receive a disconnect message,  then close everything

                var dataSegment = new ArraySegment <byte>(buffer.GetBuffer(), 0, msgSize);
                if (Utils.Equal(dataSegment, Goodby))
                {
                    open = false;
                    Disconnected?.Invoke();
                    throw new EndOfStreamException();
                }

                return((byte)Channels.Reliable);
            }
        }
Esempio n. 9
0
        /// <summary>
        ///     Open up the port and listen for connections
        ///     Use in servers.
        /// </summary>
        /// <exception>If we cannot start the transport</exception>
        /// <returns></returns>
        public override UniTask ListenAsync()
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)
                {
                    DualMode = true
                };
                socket.Bind(new IPEndPoint(IPAddress.IPv6Any, Port));

                // transport started
                Started.Invoke();

                ListenCompletionSource = AutoResetUniTaskCompletionSource.Create();
                return(ListenCompletionSource.Task);
            }
            catch (Exception ex)
            {
                return(UniTask.FromException(ex));
            }
        }
Esempio n. 10
0
        public override UniTask ListenAsync()
        {
            if (!EpicManager.Initialized)
            {
                if (Logger.logEnabled)
                {
                    if (transportDebug)
                    {
                        DebugLogger.RegularDebugLog("Epic not initialized. Server could not be started.");
                    }
                }

                return(UniTask.FromCanceled());
            }

            _server = new Server(this, _epicOptions);

            _server.StartListening();

            _listenCompletionSource = AutoResetUniTaskCompletionSource.Create();

            return(_listenCompletionSource.Task);
        }
Esempio n. 11
0
        /// <summary>
        ///     Connect to server.
        /// </summary>
        /// <returns></returns>
        public async UniTask ConnectAsync()
        {
            Options.ConnectionAddress.ToString(out string productId);

#if UNITY_EDITOR
            if (Logger.logEnabled)
#endif
            if (Transport.transportDebug)
            {
                DebugLogger.RegularDebugLog($"[Client] - attempting connection to {productId}");
            }

            if (_initialWait)
            {
                // This allows us to dump epic back end of filled up messages
                // after disconnecting from host.
                await UniTask.Delay(2 * 1000);

                _initialWait = false;
            }

            try
            {
                // Send a message to server to initiate handshake connection
                SendInternal(Options.ConnectionAddress, InternalMessage.Connect, SocketName);

                _connectedComplete = AutoResetUniTaskCompletionSource.Create();

                while (
                    await UniTask.WhenAny(_connectedComplete.Task,
                                          UniTask.Delay(TimeSpan.FromSeconds(Math.Max(1, Options.ConnectionTimeOut)))) != 0)
                {
#if UNITY_EDITOR
                    if (Logger.logEnabled)
#endif
                    if (Transport.transportDebug)
                    {
                        DebugLogger.RegularDebugLog(
                            $"[Client] - Connection to {productId} timed out.", LogType.Error);
                    }

                    Error.Invoke(Result.LobbyInviteFailed,
                                 $"[Client] - Connection to {productId} timed out.");

                    Disconnect();

                    return;
                }

                // Everything went good let's just return.
                // We need to switch to main thread for some reason.
                await UniTask.SwitchToMainThread();
            }
            catch (FormatException)
            {
                Error?.Invoke(Result.InvalidProductUserID,
                              $"[Client] - Connection string was not in the correct format.");

#if UNITY_EDITOR
                if (Logger.logEnabled)
#endif
                if (Transport.transportDebug)
                {
                    DebugLogger.RegularDebugLog(
                        "[Client] - Connection string was not in the right format. Did you enter a ProductId?",
                        LogType.Error);
                }
            }
            catch (Exception ex)
            {
                Error?.Invoke(Result.NotFound, $"Error: {ex.Message}");

#if UNITY_EDITOR
                if (Logger.logEnabled)
#endif
                if (Transport.transportDebug)
                {
                    DebugLogger.RegularDebugLog($"[Client] - Error: {ex.Message}", LogType.Error);
                }

                Disconnect();
            }
        }