Exemplo n.º 1
0
        public async Task ShouldJoinMatchmaker()
        {
            var session = await _client.AuthenticateCustomAsync($"{Guid.NewGuid()}");

            await _socket.ConnectAsync(session);

            var matchmakerTicket = await _socket.AddMatchmakerAsync("*");

            Assert.NotNull(matchmakerTicket);
            Assert.NotEmpty(matchmakerTicket.Ticket);
        }
Exemplo n.º 2
0
        public async void Socket_AwaitedTasks_AreCanceled()
        {
            var id      = Guid.NewGuid().ToString();
            var session = await _client.AuthenticateCustomAsync(id);

            await _socket.ConnectAsync(session);

            var matchmakerTask1 = _socket.AddMatchmakerAsync("+label.foo:\"val\"", 15, 20);
            var matchmakerTask2 = _socket.AddMatchmakerAsync("+label.bar:\"val\"", 15, 20);
            await _socket.CloseAsync();

            await Assert.ThrowsAsync <TaskCanceledException>(() => Task.WhenAll(matchmakerTask1, matchmakerTask2));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Adds user to matchmaking queue with given params.
        /// Returns matchmaker ticket on succes or null on failure.
        /// </summary>
        public static async Task <IMatchmakerTicket> EnterQueueAsync(ISocket socket, MatchmakingParams matchmakingParams)
        {
            if (matchmakingParams == null)
            {
                Debug.LogError("Matchmaking params cannot be null");
                return(null);
            }

            try
            {
                // Acquires matchmaking ticket used to join a match
                IMatchmakerTicket ticket = await socket.AddMatchmakerAsync(
                    matchmakingParams.query,
                    matchmakingParams.minUserCount,
                    matchmakingParams.maxUserCount,
                    matchmakingParams.stringProperties,
                    matchmakingParams.numericProperties);

                return(ticket);
            }
            catch (Exception e)
            {
                Debug.LogWarning("An error has occured while joining the matchmaker: " + e);
                return(null);
            }
        }
Exemplo n.º 4
0
    /**
     * private async void Awake()
     * {
     *  Debug.Log("NakamaTest: Awake");
     *  var authtoken = ""; // PlayerPrefs.GetString(PrefKeyName);
     *  Debug.Log("PlayerPrefsGetString: " + authtoken);
     *  if (!string.IsNullOrEmpty(authtoken))
     *  {
     *      //Debug.Log("Auth token was not null or open!");
     *      var session = Session.Restore(authtoken);
     *      //Debug.Log(new DateTime(session.ExpireTime));
     *      if (!session.IsExpired)
     *      {
     *          _session = session;
     *          Debug.Log(_session);
     *          Debug.Log("Hit this weird place.");
     *          return;
     *      }
     *  }
     *  //var deviceid = SystemInfo.deviceUniqueIdentifier;
     *  var email = "*****@*****.**";
     *  var password = "******";
     *  var username = "******";
     *  _session = await _client.AuthenticateEmailAsync(email, password, username, false);
     *  //PlayerPrefs.SetString(PrefKeyName, _session.AuthToken);
     *  _socket = _client.CreateWebSocket();
     *  _socket.OnConnect += (sender, args) =>
     *  {
     *      Debug.Log("Socket connected.");
     *  };
     *  _socket.OnDisconnect += (sender, args) =>
     *  {
     *      Debug.Log("Socket disconnected.");
     *  };
     *  await _socket.ConnectAsync(_session);
     *  Debug.Log(_session);
     *  Debug.Log(new DateTime(_session.ExpireTime));
     * }
     **/

    public async void AttemptMatchmake()
    {
        Debug.Log("Begin Attempted Matchmaking!");
        var query    = "*";
        var minCount = 2;
        var maxCount = 2;


        var matchmakerTicket = await _socket.AddMatchmakerAsync(
            query, minCount, maxCount);

        _socket.OnMatchmakerMatched += async(_, matched) =>
        {
            Debug.LogFormat("Received MatchmakerMatched message: {0}", matched);
            var opponents = string.Join(",", matched.Users); // printable list.
            Debug.LogFormat("Matched opponents: {0}", opponents);

            myMatch = await _socket.JoinMatchAsync(matched);

            if (myMatch != null)
            {
                Debug.Log("Match ID: " + myMatch.Id);
            }
            else
            {
                Debug.Log("NO MATCH!");
            }
            CreateMessageListener();
        };
    }
Exemplo n.º 5
0
    public async void MatchMakingStart()
    {
        _timeProbesReceived = 0;
        lock (_users)
        {
            _users.Clear();
        }

        Local.NameUser   = Composition.DataAccount.NameUser;
        Local.Seed       = UnityEngine.Random.value;
        Local.BallColor  = Composition.DataMeta.BallColor;
        Local.BallRadius = Composition.DataMeta.BallRadius;
        Local.BallSpeedX = Composition.ControllerSim.Frame.BallSpeedX;
        Local.BallSpeedY = Composition.ControllerSim.Frame.BallSpeedY;

        await _netSocket.AddMatchmakerAsync(
            "*",
            2,
            2,
            new Dictionary <string, string>(),
            new Dictionary <string, double>
        {
            { KEY_SEED, Local.Seed },
            { KEY_BALL_COLOR_R, Local.BallColor.r },
            { KEY_BALL_COLOR_G, Local.BallColor.g },
            { KEY_BALL_COLOR_B, Local.BallColor.b },
            { KEY_BALL_RADIUS, Local.BallRadius },
            { KEY_BALL_SPEED_X, Local.BallSpeedX },
            { KEY_BALL_SPEED_Y, Local.BallSpeedY },
        });
    }
Exemplo n.º 6
0
        private async void Start()
        {
            var deviceId = SystemInfo.deviceUniqueIdentifier;
            var session  = await _client.AuthenticateDeviceAsync(deviceId);

            Debug.Log(session);

            _socket                = _client.NewSocket();
            _socket.Connected     += () => Debug.Log("Socket connected.");
            _socket.Closed        += () => Debug.Log("Socket closed.");
            _socket.ReceivedError += Debug.LogError;

            IUserPresence self = null;
            var           connectedOpponents = new List <IUserPresence>(2);

            _socket.ReceivedMatchmakerMatched += async matched =>
            {
                Debug.LogFormat("Matched result: {0}", matched);
                var match = await _socket.JoinMatchAsync(matched);

                self = match.Self;
                Debug.LogFormat("Self: {0}", self);
                connectedOpponents.AddRange(match.Presences);
            };
            _socket.ReceivedMatchPresence += presenceEvent =>
            {
                foreach (var presence in presenceEvent.Leaves)
                {
                    connectedOpponents.Remove(presence);
                }
                connectedOpponents.AddRange(presenceEvent.Joins);
                // Remove yourself from connected opponents.
                connectedOpponents.Remove(self);
                Debug.LogFormat("Connected opponents: [{0}]", string.Join(",\n  ", connectedOpponents));
            };
            await _socket.ConnectAsync(session);

            Debug.Log("After socket connected.");
            await _socket.AddMatchmakerAsync("*", 2, 2);


            // NOTE As an example create a second user and socket to matchmake against.
            var deviceId2 = Guid.NewGuid().ToString();
            var session2  = await _client.AuthenticateDeviceAsync(deviceId2);

            var socket2 = _client.NewSocket();

            socket2.ReceivedMatchmakerMatched += async matched => await socket2.JoinMatchAsync(matched);

            await socket2.ConnectAsync(session2);

            await socket2.AddMatchmakerAsync("*", 2, 2);

            await Task.Delay(TimeSpan.FromSeconds(10)); // disconnect after 10 seconds.

            Debug.Log("After delay socket2 closed.");
            await socket2.CloseAsync();
        }
Exemplo n.º 7
0
    async void Start()
    {
        var deviceid = SystemInfo.deviceUniqueIdentifier;
        // NOTE should cache a user session.
        var session = await _client.AuthenticateDeviceAsync(deviceid);

        Debug.LogFormat("Session '{0}'", session);

        _socket = _client.CreateWebSocket();

        IUserPresence self = null;
        var           connectedOpponents = new List <IUserPresence>(0);

        _socket.OnMatchmakerMatched += async(sender, matched) =>
        {
            Debug.LogFormat("Matched '{0}'", matched);
            var match = await _socket.JoinMatchAsync(matched);

            self = match.Self;
            Debug.LogFormat("Self '{0}'", self);
            connectedOpponents.AddRange(match.Presences);

            // NOTE shows how to send match state messages.
            var newState = new Dictionary <string, string> {
                { "hello", "world" }
            }.ToJson();
            _socket.SendMatchState(match.Id, 0, newState); // Send to all connected users.
        };
        _socket.OnMatchPresence += (sender, presenceChange) =>
        {
            connectedOpponents.AddRange(presenceChange.Joins);
            foreach (var leave in presenceChange.Leaves)
            {
                connectedOpponents.RemoveAll(item => item.SessionId.Equals(leave.SessionId));
            }
            ;
            // Remove yourself from connected opponents.
            connectedOpponents.RemoveAll(item => {
                return(self != null && item.SessionId.Equals(self.SessionId));
            });
        };
        _socket.OnMatchState += (sender, message) =>
        {
            var enc = System.Text.Encoding.UTF8;
            Debug.LogFormat("Match state '{0}'", enc.GetString(message.State));
        };
        _socket.OnConnect    += (sender, evt) => Debug.Log("Socket connected.");
        _socket.OnDisconnect += (sender, evt) => Debug.Log("Socket disconnected.");

        await _socket.ConnectAsync(session);

        int minCount         = 2;
        int maxCount         = 8;
        var matchmakerTicket = await _socket.AddMatchmakerAsync("*", minCount, maxCount);

        Debug.LogFormat("Matchmaker ticket '{0}'", matchmakerTicket);
    }
        // -------------------------------------------

        /*
         * Starts looking for a match with a given number of minimum players.
         */
        public async Task FindMatch(string roomName, int minPlayers, int maxPlayers)
        {
            var matchmakingProperties = new Dictionary <string, string>
            {
                { "roomname", roomName }
            };

            // Add this client to the matchmaking pool and get a ticket.
            var matchmakerTicket = await Socket.AddMatchmakerAsync("+properties.roomname:" + roomName, minPlayers, maxPlayers, matchmakingProperties);

            m_currentMatchmakingTicket = matchmakerTicket.Ticket;
        }
        private async void Start()
        {
            _player = FindObjectOfType <NetworkCharacter>();

            //BASIC
            await AuthSession();
            await InitSocket();

            await _socket.ConnectAsync(_session);

            //MATCHMAKING
            SubscribeSocketsEvents();
            Debug.Log("After socket connected.");
            await _socket.AddMatchmakerAsync("*", 2, 4);
        }
Exemplo n.º 10
0
    public async Task <bool> StartMatchMaker(int matchType, int playerCount)
    {
        var minCount          = playerCount;
        var maxCount          = playerCount;
        var numericProperties = new Dictionary <string, double>()
        {
            { "matchType", matchType }
        };
        string query;

        switch (matchType)
        {
        case 0:
            query = "*";
            break;

        case 1:
            query = "-properties.matchType:2 -properties.matchType:3";
            break;

        case 2:
            query = "-properties.matchType:1 -properties.matchType:3";
            break;

        case 3:
            query = "-properties.matchType:1 -properties.matchType:2";
            break;

        default:
            query = "*";
            break;
        }

        try
        {
            _matchmakerTicket = await _socket.AddMatchmakerAsync(query, minCount, maxCount, null, numericProperties);
        }
        catch (Exception)
        {
            return(false);
        }

        return(true);
    }
    // +++ unity callbacks ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    async void Start()
    {
        Init();

        // create client
        _client   = new Client(_key, _host, 7350, false);
        _playerId = _userManager.GetPlayerId();

        // create session
        _session = await _client.AuthenticateDeviceAsync(_playerId);

        // Init List of connected users
        _connectedUsers = new List <IUserPresence>(0);

        // create socket
        _socket = _client.CreateWebSocket();

        // subscribe to socket events
        _socket.OnMatchmakerMatched += OnMatchmakerMatched;
        _socket.OnConnect           += OnConnect;
        _socket.OnDisconnect        += OnDisconnect;
        _socket.OnMatchPresence     += OnMatchPresence;
        _socket.OnMatchState        += OnMatchState;

        // wait for socket connection
        await _socket.ConnectAsync(_session);

        Debug.Log("Socket connected");

        // wait for match maker ticket
        _matchMakerTicket = await _socket.AddMatchmakerAsync(
            "*",
            NUMPLAYERS,
            NUMPLAYERS);

        Debug.Log("Matchmaker ticket received");

        // wait for 2 players to connect
        StartCoroutine(WaitForNumberOfPlayers(NUMPLAYERS));
    }
Exemplo n.º 12
0
    public async Task CreateMatchMakerMatchAsync()
    {
        // Init List of connected users
        _connectedUsers = new List <IUserPresence>(0);

        // create socket
        _socket = _client.CreateWebSocket();

        _socket.OnMatchmakerMatched += OnMatchmakerMatched;
        _socket.OnConnect           += OnConnect;
        _socket.OnDisconnect        += OnDisconnect;
        _socket.OnMatchPresence     += OnMatchPresence;
        _socket.OnMatchState        += OnMatchState;

        // wait for socket connection
        await _socket.ConnectAsync(_session);

        // MatchMaker Parameters
        var query = "*";

        _matchMakerTicket = await _socket.AddMatchmakerAsync(query, _minPlayers, _maxPlayers);
    }
    // Start is called before the first frame update
    async void Start()
    {
        // Access the gameSceneController
        gameSceneController = FindObjectOfType <GameSceneController>();

        // Create the client
        var client = new Client("http", gameHost, gamePort, gameKey);

        const string email    = "*****@*****.**";
        const string password = "******";
        var          session  = await client.AuthenticateEmailAsync(email, password);

        Debug.Log(session);

        socket            = client.NewSocket();
        socket.Connected += () => Debug.Log("Socket connected.");
        socket.Closed    += () => Debug.Log("Socket closed");

        socket.ReceivedChannelMessage += async matched =>
        {
            Debug.LogFormat("Match: {0}", matched);
        };

        await socket.ConnectAsync(session);

        await socket.AddMatchmakerAsync("*", 2, 2);

        var channel = await socket.JoinChatAsync(RoomName, ChannelType.Room);

        Debug.LogFormat("Join chat channel: {0}", channel);

        var content = new Dictionary <string, string> {
            { "hello", "world" }
        }.ToJson();

        _ = socket.WriteChatMessageAsync(channel, content);
    }