/// <summary>
        /// Restores session or tries to establish a new one.
        /// Invokes <see cref="OnConnectionSuccess"/> or <see cref="OnConnectionFailure"/>.
        /// </summary>
        /// <returns></returns>
        public async Task <AuthenticationResponse> ConnectAsync()
        {
            AuthenticationResponse response = await RestoreTokenAsync();

            switch (response)
            {
            case AuthenticationResponse.Authenticated:
                OnConnectionSuccess?.Invoke();
                break;

            case AuthenticationResponse.NewAccountCreated:
                OnNewAccountCreated?.Invoke();
                OnConnectionSuccess?.Invoke();
                break;

            case AuthenticationResponse.Error:
                OnConnectionFailure?.Invoke();
                break;

            default:
                Debug.LogError("Unhandled response received: " + response);
                break;
            }
            return(response);
        }
Esempio n. 2
0
        public void Connect(IPEndPoint hostEndpoint, OnConnectionEstablished onConnectionEstablished = null,
                            OnConnectionFailure onConnectionFailure = null, OnDisconnected onDisconnected = null)
        {
            var connectionId = _transporter.Connect(hostEndpoint);

            _connections[connectionId] = new ConnectionRegistration {
                OnConnectionEstablished = onConnectionEstablished ?? EmptyOnConnectionEstablished,
                OnDisconnected          = onDisconnected ?? EmptyOnDisconnected
            };
        }
Esempio n. 3
0
        public ConnectionId Connect(IPEndPoint hostEndpoint,
                                    ApprovalSecret approvalSecret,
                                    OnConnectionEstablished onConnectionEstablished = null,
                                    OnConnectionFailure onConnectionFailure         = null,
                                    OnDisconnected onDisconnected = null)
        {
            var connectionId = _connectionIdPool.Take();

            _transporter.Connect(connectionId, approvalSecret, hostEndpoint);
            _connections[connectionId] = new ConnectionRegistration {
                Endpoint = hostEndpoint,
                OnConnectionEstablished = onConnectionEstablished ?? EmptyOnConnectionEstablished,
                OnConnectionFailure     = onConnectionFailure ?? EmptyOnConnectionFailure,
                OnDisconnected          = onDisconnected ?? EmptyOnDisconnected,
                Status = ConnectionStatus.Pending,
            };
            return(connectionId);
        }
        public void Connect(IPEndPoint hostEndpoint,
                            OnConnectionEstablished onConnectionEstablished = null,
                            OnConnectionFailure onConnectionFailure         = null,
                            OnDisconnected onDisconnected = null)
        {
            var connectionRegistration = new ConnectionRegistration();

            connectionRegistration.Timestamp               = Time.realtimeSinceStartup;
            connectionRegistration.ConnectionId            = ConnectionId.NoConnection;
            connectionRegistration.PublicEndpoint          = hostEndpoint;
            connectionRegistration.OnConnectionEstablished = onConnectionEstablished ?? EmptyOnConnectionEstablished;
            connectionRegistration.OnConnectionFailure     = onConnectionFailure ?? EmptyOnConnectionFailure;
            connectionRegistration.OnDisconnected          = onDisconnected ?? EmptyOnDisconnected;

            var punchId = _natPunchClient.Punch(hostEndpoint, OnPunchSuccess, OnPunchFailure);

            _punchAttempts.Add(punchId, connectionRegistration);
        }
Esempio n. 5
0
 public void JoinServer(IPEndPoint endPoint,
                        int clientPort = -1,
                        OnConnectionEstablished onEstablished = null,
                        OnConnectionFailure onFailure         = null, OnDisconnected onDisconnected = null)
 {
     Shutdown();
     _isJoinInProgress = true;
     _isSingleplayer   = false;
     _coroutineScheduler.Run(_networkClient.Join(endPoint,
                                                 clientPort,
                                                 (connectionId, endpoint) => {
         _authorityConnectionId = connectionId;
         _isJoinInProgress      = false;
         if (onEstablished != null)
         {
             onEstablished(connectionId, endPoint);
         }
     },
                                                 onFailure,
                                                 onDisconnected));
 }
        public ConnectionId Connect(IPEndPoint hostEndpoint,
                                    ApprovalSecret approvalSecret,
                                    OnConnectionEstablished onConnectionEstablished = null,
                                    OnConnectionFailure onConnectionFailure         = null,
                                    OnDisconnected onDisconnected = null)
        {
            var connectionId           = _connectionIdPool.Take();
            var connectionRegistration = _connectionRegistrationPool.Take();

            connectionRegistration.Instance.Timestamp               = Time.realtimeSinceStartup;
            connectionRegistration.Instance.ConnectionId            = connectionId;
            connectionRegistration.Instance.ApprovalSecret          = approvalSecret;
            connectionRegistration.Instance.PublicEndpoint          = hostEndpoint;
            connectionRegistration.Instance.OnConnectionEstablished = onConnectionEstablished ?? EmptyOnConnectionEstablished;
            connectionRegistration.Instance.OnConnectionFailure     = onConnectionFailure ?? EmptyOnConnectionFailure;
            connectionRegistration.Instance.OnDisconnected          = onDisconnected ?? EmptyOnDisconnected;

            var punchId = _natPunchClient.Punch(hostEndpoint, OnPunchSuccess, OnPunchFailure);

            _punchAttempts.Add(punchId, connectionRegistration);

            return(connectionId);
        }
Esempio n. 7
0
        private void OnSteamClientConnected(SteamClient.ConnectedCallback callback)
        {
            if (callback.Result != EResult.OK)
            {
                OnConnectionFailure?.Invoke(this, string.Format("Unable to connect to Steam: {0}", callback.Result));

                Disconnect();
                return;
            }

            OnConnectionSuccess?.Invoke(this, string.Format("Connected to Steam! Logging in '{0}'...", m_SteamUserName));

            byte[] sentryHash = null;
            if (File.Exists(Settings.Default.SentryFileLocation))
            {
                // if we have a saved sentry file, read and sha-1 hash it
                byte[] sentryFile = File.ReadAllBytes(Settings.Default.SentryFileLocation);
                sentryHash = CryptoHelper.SHAHash(sentryFile);
            }

            m_steamUser.LogOn(new SteamUser.LogOnDetails
            {
                Username = m_SteamUserName,
                Password = m_SteamPassword.ToPlainText(),

                // this value will be null (which is the default) for our first logon attempt
                AuthCode = m_AuthCode,

                // if the account is using 2-factor auth, we'll provide the two factor code instead
                // this will also be null on our first logon attempt
                TwoFactorCode = m_TwoFactorAuth,

                // our subsequent logons use the hash of the sentry file as proof of ownership of the file
                // this will also be null for our first (no authcode) and second (authcode only) logon attempts
                SentryFileHash = sentryHash,
            });
        }
Esempio n. 8
0
    public void Connect(IPEndPoint remoteEndPoint, OnConnectionEstablished onEstablished,
                        OnConnectionFailure onFailure, OnDisconnected onDisconnected)
    {
        _ramnet.MessageRouter.ClearHandlers();
        _ramnet.MessageRouter
        .RegisterHandler <BasicMessage.Pong>(OnServerClockSync)
        .RegisterHandler <BasicMessage.ReplicatePreExistingObject>((connectionId, endpoint, message) => {
            Debug.Log("replicating existing instance " + message.GlobalObjectId);
            var instance = _ramnet.PreExistingObjects[message.GlobalObjectId];
            Debug.Log("instance found: " + instance);
            _ramnet.ReplicatedObjectStore.ReplicateExistingInstance(message.ObjectRole, connectionId, instance,
                                                                    message.NetworkObjectId, message.GlobalObjectId);
        })
        .RegisterHandler <BasicMessage.CreateObject>((connectionId, endpoint, message, reader) => {
            var replicatedObject = _ramnet.ReplicatedObjectStore.AddReplicatedInstance(
                message.ObjectType,
                message.ObjectRole,
                message.ObjectId,
                connectionId);
            Debug.Log("Creating object with id " + message.ObjectId, replicatedObject.GameObject);
            _ramnet.ReplicatedObjectStore.DispatchMessages(connectionId, message.ObjectId,
                                                           message.AdditionalData, message.AdditionalData.LengthBytes);
            replicatedObject.Activate();
            if (message.ObjectType == ObjectTypes.Player && message.ObjectRole.IsOwner())
            {
                _camera.Target = replicatedObject.GameObject.GetComponent <PlayerSimulation>();
            }
        })
        .RegisterHandler <BasicMessage.ToObject>((connectionId, endpoint, message, reader) => {
            _ramnet.ReplicatedObjectStore.DispatchMessage(connectionId, message.ReceiverId,
                                                          reader);
        })
        .RegisterHandler <BasicMessage.DeleteObject>((connectionId, endpoint, message, reader) => {
            _ramnet.ReplicatedObjectStore.RemoveReplicatedInstance(connectionId, message.ObjectId);
        });
        _ramnet.GroupRouter.ClearConnectionHandlers();

        if (_transporter.Status == TransporterStatus.Closed)
        {
            var transportConfig = new NetPeerConfiguration("RigidbodyParty");
            transportConfig.MaximumConnections = 64;
            _transporter.Open(transportConfig);
        }

        Debug.Log("Connecting to " + remoteEndPoint);
        _initialSyncDone = false;
        _ramnet.ConnectionManager.Connect(remoteEndPoint,
                                          (connId, endpoint) => {
            OnConnectionEstablished(connId, endpoint);
            onEstablished(connId, endpoint);
        },
                                          (endpoint, exception) => {
            OnConnectionFailure(endpoint);
            onFailure(endpoint, exception);
        },
                                          connId => {
            OnDisconnected(connId);
            onDisconnected(connId);
        });
        _camera.gameObject.SetActive(true);
    }
Esempio n. 9
0
        public IEnumerator <WaitCommand> Join(IPEndPoint endPoint,
                                              int clientPort = -1,
                                              OnConnectionEstablished onEstablished = null,
                                              OnConnectionFailure onFailure         = null,
                                              OnDisconnected onDisconnected         = null)
        {
            _outstandingPings.Clear();
            _frameId          = 0;
            _isJoinInProgress = true;

            var    sessionIdResult = new AsyncResult <JoinResponse>();
            string password        = null;

            _masterServerClient.Client.Join(endPoint, password, (statusCode, s) => {
                sessionIdResult.SetResult(s);
            });

            while (!sessionIdResult.IsResultAvailable)
            {
                yield return(WaitCommand.WaitForNextFrame);
            }

            if (sessionIdResult.Result != null)
            {
                _sessionId = sessionIdResult.Result.SessionId;

                var netConfig = new NetPeerConfiguration(NetworkConfig.GameId);
                // Kind of arbitrary, we need to have enough room for connection attempts
                // and cancellation running simultaneously but we don't need to have an unlimited number
                netConfig.MaximumConnections = 16;
                if (clientPort > -1)
                {
                    netConfig.Port = clientPort;
                }
                _transporter.Open(netConfig);

                var approvalSecret = new ApprovalSecret(_sessionId.Value.Value);
                _hostConnectionId = _networkSystems.ConnectionManager.Connect(endPoint,
                                                                              approvalSecret,
                                                                              (connId, endpoint) => {
                    _isJoinInProgress = false;
                    OnConnectionEstablished(connId, endpoint);
                    if (onEstablished != null)
                    {
                        onEstablished(connId, endpoint);
                    }
                },
                                                                              (endpoint, exception) => {
                    _isJoinInProgress = false;
                    OnConnectionFailure(endpoint, exception);
                    if (onFailure != null)
                    {
                        onFailure(endpoint, exception);
                    }
                },
                                                                              connId => {
                    _isJoinInProgress = false;
                    OnDisconnected(connId);
                    if (onDisconnected != null)
                    {
                        onDisconnected(connId);
                    }
                });
            }
            else
            {
                OnConnectionFailure(endPoint, new Exception("Master server did not allow join on " + endPoint));
            }
        }
Esempio n. 10
0
        public virtual void Connect(BTPeer peer, int numberOfRetries = 5)
        {
            Task.Run(async() =>
            {
                try
                {
                    socket = peer.Device.CreateRfcommSocketToServiceRecord(BluetoothServer.ServiceUUID);
                    await Task.Delay(100);
                    socket.Connect();
                    await Task.Delay(250);

                    if (socket.IsConnected)
                    {
                        Log.Debug(_tag, $"Client: Connection accepted to {socket.RemoteDevice.Address}.");
                        OnConnectionSuccess?.Invoke(this, EventArgs.Empty);
                        IsConnected = true;
                    }
                    else
                    {
                        OnConnectionFailure?.Invoke(this, EventArgs.Empty);
                        IsConnected = false;
                        if (numberOfRetries > 0)
                        {
                            Log.Debug(_tag, $"Client: Connection unsuccessful; retrying in {SocketTimeout} ms.");
                            await Task.Delay(SocketTimeout)
                            .ContinueWith((_) => { Connect(peer, numberOfRetries - 1); })
                            .ConfigureAwait(false);
                        }
                        else
                        {
                            Log.Debug(_tag, "Client: Connection unsuccessful, retry limit exhausted.");
                        }
                        return;
                    }

                    inStream  = new DataInputStream(socket.InputStream);
                    outStream = new DataOutputStream(socket.OutputStream);

                    BluetoothCore.RunSendingLooper(this);

                    Task.Delay(500)
                    .ContinueWith(_ =>
                                  SendMessage(new Message(MsgType.Notify,
                                                          $"{CONFIRM_AS_CLIENT}{NEXT}{socket.RemoteDevice.Address}")))
                    .LaunchAsOrphan();

                    //await Task.Delay(100);
                    var ListeningLoop = Task.Run((Action)Listen); // When finished, *should* mean that it's received its stop signal and is thus ready to close.

                    //foreach (var teammate in HeyYou.MyTeammates.TeamMembers)
                    //{
                    //    var teamMate = teammate as CommsContact;
                    //    if (teamMate == null) continue;
                    //    if (teamMate.IPaddress == socket.RemoteDevice.Address) continue; // Don't bother suggesting themselves as a teammate!
                    //    SendMessage(new Message(MsgType.Notify, $"{SUGGEST_TEAMMATE}{NEXT}{teamMate.IPaddress}"));
                    //}

                    await ListeningLoop;
                }
                catch (Exception e)
                {
                    Log.Debug(_tag, e.ToString());
                }
                finally
                {
                    Log.Debug(_tag, "Closing client connection.");
                    //socket.Close();
                    //IsConnected = false;
                    Disconnect();
                }
            });
        }