private 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.OnConnect       += (sender, evt) => Debug.Log("Socket connected.");
        _socket.OnDisconnect    += (sender, evt) => Debug.Log("Socket disconnected.");
        _socket.OnMatchPresence += (sender, presenceChange) =>
        {
            connectedOpponents.AddRange(presenceChange.Joins);
            foreach (var leave in presenceChange.Leaves)
            {
                connectedOpponents.RemoveAll(item => item.SessionId.Equals(leave.SessionId));
            }
            ;
            // Remove ourself 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));
        };

        await _socket.ConnectAsync(session);

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

        Debug.LogFormat("Matchmaker ticket '{0}'", matchmakerTicket);
    }
Beispiel #2
0
        public async Task StartNotificationListener()
        {
            _clientSocket = PlatformServices.SocketFactory.GetSocket();
            await _clientSocket.ConnectAsync(_settings.Host, _settings.TcpPort);

            var stream = _clientSocket.GetInputStream();

            ListenForNotifications(stream);
        }
Beispiel #3
0
    async void Start()
    {
        //Connect to master server
        client = new Client("http", "192.168.2.131", 7350, "defaultkey");

        //Authenticate user and receive session object
        var deviceId = PlayerPrefs.GetString("nakama.deviceid");

        if (string.IsNullOrEmpty(deviceId))
        {
            deviceId = SystemInfo.deviceUniqueIdentifier;
            PlayerPrefs.SetString("nakama.deviceid", deviceId); // cache device id.
        }
        session = await client.AuthenticateDeviceAsync(deviceId);

        Debug.LogFormat("New user: {0}, {1}", session.Created, session);

        //Get current display name from account
        var account = await client.GetAccountAsync(session);

        var user = account.User;

        Debug.LogFormat("User id '{0}' username '{1}'", user.Id, user.Username);
        Debug.LogFormat("User wallet: '{0}'", account.Wallet);
        displayNameField.text = user.DisplayName;

        //Create socket to communicate with the server
        socket            = client.NewSocket();
        socket.Connected += () =>
        {
            Debug.Log("Socket connected.");
        };
        socket.Closed += () =>
        {
            Debug.Log("Socket closed.");
        };
        await socket.ConnectAsync(session);

        //Subscribe to match presence event
        var connectedOpponents = new List <IUserPresence>(2);

        socket.ReceivedMatchPresence += presenceEvent =>
        {
            foreach (var presence in presenceEvent.Leaves)
            {
                connectedOpponents.Remove(presence);
            }
            connectedOpponents.AddRange(presenceEvent.Joins);
            // Remove yourself from connected opponents.
            // if (match != null && match.Presences != null)
            //     foreach (var self in match.Presences)
            //         if (self != null && connectedOpponents.Contains(self))
            //             connectedOpponents.Remove(self);
            Debug.LogFormat("Connected opponents: [{0}]", string.Join(",\n  ", connectedOpponents));
        };
    }
        private async void Start()
        {
            var deviceId = SystemInfo.deviceUniqueIdentifier;
            var session  = await _client.AuthenticateDeviceAsync(deviceId);

            Debug.LogFormat("Session user id: '{0}'", session.UserId);

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

            var roomUsers = new List <IUserPresence>(10);

            _socket.ReceivedChannelPresence += presenceEvent =>
            {
                foreach (var presence in presenceEvent.Leaves)
                {
                    roomUsers.Remove(presence);
                }

                roomUsers.AddRange(presenceEvent.Joins);
                Debug.LogFormat("Room users: [{0}]", string.Join(",\n  ", roomUsers));
            };

            var messageList = new List <IApiChannelMessage>(100);

            _socket.ReceivedChannelMessage += message =>
            {
                Debug.LogFormat("Received message: '{0}'", message);
                AddListSorted(messageList, message);
                Debug.LogFormat("Message list: {0}", string.Join(",\n  ", messageList));
            };
            await _socket.ConnectAsync(session);

            Debug.Log("After socket connected.");

            // Join chat channel.
            var channel = await _socket.JoinChatAsync(RoomName, ChannelType.Room);

            roomUsers.AddRange(channel.Presences);
            Debug.LogFormat("Joined chat channel: {0}", channel);

            // Send many chat messages.
            var content = new Dictionary <string, string> {
                { "hello", "world" }
            }.ToJson();

            _ = _socket.WriteChatMessageAsync(channel, content);
            _ = _socket.WriteChatMessageAsync(channel, content);
            _ = _socket.WriteChatMessageAsync(channel, content);
            _ = _socket.WriteChatMessageAsync(channel, content);
            _ = _socket.WriteChatMessageAsync(channel, content);
            _ = _socket.WriteChatMessageAsync(channel, content);
        }
Beispiel #5
0
    private async void Awake()
    {
        var deviceid = SystemInfo.deviceUniqueIdentifier;
        var session  = await _client.AuthenticateDeviceAsync(deviceid);

        _socket               = _client.CreateWebSocket();
        _socket.OnConnect    += (sender, args) => Debug.Log("Socket connected.");
        _socket.OnDisconnect += (sender, args) => Debug.Log("Socket disconnected.");

        await _socket.ConnectAsync(session);
    }
Beispiel #6
0
    private async void Awake()
    {
        var deviceid = SystemInfo.deviceUniqueIdentifier;
        var session  = await _client.AuthenticateDeviceAsync(deviceid);

        _socket        = _client.CreateWebSocket();
        _socket.Logger = new UnityLogger();
        _socket.Trace  = true;

        await _socket.ConnectAsync(session);
    }
Beispiel #7
0
    async void Awake()
    {
        // Authenticate with device id for a user account.
        var deviceid = SystemInfo.deviceUniqueIdentifier;
        var session  = await _client.AuthenticateDeviceAsync(deviceid);

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

        await _socket.ConnectAsync(session);
    }
Beispiel #8
0
 public async Task ConnectAsync()
 {
     try
     {
         await _socket.ConnectAsync();
     }
     catch (Exception ex)
     {
         throw new TransportException(TransportError.ConnectError, ex);
     }
     StartReceive();
 }
Beispiel #9
0
        public async Task ShouldCreateMatch()
        {
            var session = await _client.AuthenticateCustomAsync($"{Guid.NewGuid()}");

            await _socket.ConnectAsync(session);

            var match = await _socket.CreateMatchAsync();

            Assert.NotNull(match);
            Assert.NotNull(match.Id);
            Assert.NotEmpty(match.Id);
            Assert.False(match.Authoritative);
            Assert.True(match.Size > 0);
        }
Beispiel #10
0
        public async void FollowUsers_NoUsers_AnotherUser()
        {
            var id       = Guid.NewGuid().ToString();
            var session1 = await _client.AuthenticateCustomAsync(id);

            var session2 = await _client.AuthenticateCustomAsync(id + "a");

            var completer = new TaskCompletionSource <IStatusPresenceEvent>();
            var canceller = new CancellationTokenSource();

            canceller.Token.Register(() => completer.TrySetCanceled());
            canceller.CancelAfter(Timeout);
            _socket.ReceivedStatusPresence += statuses => completer.SetResult(statuses);
            _socket.ReceivedError          += e => completer.TrySetException(e);
            await _socket.ConnectAsync(session1);

            await _socket.FollowUsersAsync(new[] { session2.UserId });

            var socket = Nakama.Socket.From(_client);
            await socket.ConnectAsync(session2);

            await socket.UpdateStatusAsync("new status change");

            var result = await completer.Task;

            Assert.NotNull(result);
            Assert.Contains(result.Joins, joined => joined.UserId.Equals(session2.UserId));
        }
        public bool Connect(AsyncSocketEventArgs eventArgs)
        {
            _notIoArgs.RemoteEndPoint = eventArgs.RemoteEndPoint;
            _notIoArgs.UserToken      = eventArgs;
            eventArgs.Error           = null;

            var isAsync = _socket.ConnectAsync(_notIoArgs);

            if (!isAsync)
            {
                NotSendCallBack(false, _notIoArgs);
            }
            return(isAsync);
        }
        private async void Awake()
        {
            _socket                = _client.NewSocket();
            _socket.Closed        += () => Debug.Log("Socket closed.");
            _socket.Connected     += () => Debug.Log("Socket connected.");
            _socket.ReceivedError += e => Debug.LogErrorFormat("Socket error: {0}", e.Message);

            var deviceId = SystemInfo.deviceUniqueIdentifier;
            var session  = await _client.AuthenticateDeviceAsync(deviceId);

            await _socket.ConnectAsync(session);

            Debug.Log("After socket connected.");
        }
    private async Task <bool> createSocket()
    {
        _socket = _client.NewSocket();

        _socket.ReceivedMatchPresence += _socket_ReceivedMatchPresence;

        _socket.ReceivedMatchState += _socket_ReceivedMatchState;

        _socket.Closed += _socket_Closed;

        await _socket.ConnectAsync(_session);

        return(true);
    }
Beispiel #14
0
        public async Task ShouldCreateSocketAndConnect()
        {
            var session = await _client.AuthenticateCustomAsync($"{Guid.NewGuid()}");

            var completer = new TaskCompletionSource <bool>();

            _socket.Connected += () => completer.SetResult(true);

            await _socket.ConnectAsync(session);

            Assert.True(await completer.Task);
            await _socket.CloseAsync();
        }
        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);
        }
Beispiel #16
0
        public async void TestFollowMassiveNumberOfUsers()
        {
            const int numFollowees = 500;

            var id1      = Guid.NewGuid().ToString();
            var session1 = await _client.AuthenticateCustomAsync(id1);

            var socket1 = Nakama.Socket.From(_client);

            await socket1.ConnectAsync(session1);

            var followeeTasks    = new List <Task>();
            var followeeSessions = new List <ISession>();

            for (int i = 0; i < numFollowees; i++)
            {
                ISocket socket     = null;
                var     followeeId = Guid.NewGuid().ToString();

                var followeeTask = await _client.AuthenticateCustomAsync(followeeId)
                                   .ContinueWith(async session => {
                    followeeSessions.Add(session.Result);
                    socket = Nakama.Socket.From(_client);
                    await socket.ConnectAsync(session.Result);
                    await socket.UpdateStatusAsync("status for " + i.ToString());
                });

                followeeTasks.Add(followeeTask);
            }


            Task.WaitAll(followeeTasks.ToArray());

            IStatus statuses = null;

            try
            {
                statuses = await socket1.FollowUsersAsync(followeeSessions.Select(session => session.UserId));
            }
            catch (ApiResponseException)
            {
                throw;
            }

            Assert.Equal(numFollowees, statuses.Presences.Count());

            await socket1.CloseAsync();
        }
Beispiel #17
0
        public async Task StartNotificationListener()
        {
            _clientSocket = PlatformServices.SocketFactory.GetSocket();
            await _clientSocket.ConnectAsync(_settings.Host, _settings.TcpPort);

            var stream = _clientSocket.GetInputStream();

            //
            // compiler complains about not waiting for results to be ready
            // we can safely ignore this because we get the results throug
            // a different channel
            //
#pragma warning disable CS4014
            ListenForNotifications(stream);
#pragma warning restore CS4014
        }
        public async Task ShouldSendRpcRoundtrip()
        {
            var session = await _client.AuthenticateCustomAsync($"{Guid.NewGuid()}");

            await _socket.ConnectAsync(session);

            const string funcid = "clientrpc.rpc";
            var          payload = new Dictionary <string, string> {
                { "hello", "world" }
            }.ToJson();
            var response = await _socket.RpcAsync(funcid, payload);

            Assert.NotNull(response);
            Assert.AreEqual(funcid, response.Id);
            Assert.AreEqual(payload, response.Payload);
        }
Beispiel #19
0
        protected override void DoInitialize()
        {
            var args = new MySocketAsyncEventArgs();

            args.RemoteEndPoint = ParseEndpointAddress(new Uri(Address), AddressFamily);
            args.Completed     += SocketOperationCompleted;
            args.UserToken      = null;

            _socket = CreateSocket(args.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _asyncOperationInProgress = true;

            if (!_socket.ConnectAsync(args))
            {
                SocketOperationCompleted(_socket, args);
            }
        }
Beispiel #20
0
    public async void JoinMatchIdAsync(string matchId)
    {
        if (matchSocket == null)
        {
            matchSocket = client.NewSocket();
            await matchSocket.ConnectAsync(session);
        }
        activeSceneMatchId = matchId;
        match = await matchSocket.JoinMatchAsync(matchId);

        EventManager.onRoomJoin.Invoke();

        //foreach (var presence in match.Presences)
        //{
        //    Debug.LogFormat("User id '{0}' name '{1}'.", presence.UserId, presence.Username);
        //}
    }
Beispiel #21
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();

        var connectedUsers = new List <IUserPresence>(0);

        _socket.OnChannelPresence += (sender, presenceChange) =>
        {
            connectedUsers.AddRange(presenceChange.Joins);
            foreach (var leave in presenceChange.Leaves)
            {
                connectedUsers.RemoveAll(item => item.SessionId.Equals(leave.SessionId));
            }
            ;

            // Print connected presences.
            var presences = string.Join(", ", connectedUsers);
            Debug.LogFormat("Presence List\n {0}", presences);
        };
        _socket.OnChannelMessage += (sender, message) =>
        {
            Debug.LogFormat("Received Message '{0}'", message);
        };
        _socket.OnConnect    += (sender, evt) => Debug.Log("Socket connected.");
        _socket.OnDisconnect += (sender, evt) => Debug.Log("Socket disconnected.");

        await _socket.ConnectAsync(session);

        // Join chat channel.
        var channel = await _socket.JoinChatAsync(RoomName, ChannelType.Room);

        connectedUsers.AddRange(channel.Presences);

        // Send chat message.
        var content = new Dictionary <string, string> {
            { "hello", "world" }
        }.ToJson();
        await _socket.WriteChatMessageAsync(channel, content);
    }
        public async Task ShouldReceiveNotification()
        {
            var session = await _client.AuthenticateCustomAsync($"{Guid.NewGuid()}");

            var completer = new TaskCompletionSource <IApiNotification>();

            _socket.ReceivedNotification += (notification) => completer.SetResult(notification);
            await _socket.ConnectAsync(session);

            var payload = new Dictionary <string, string> {
                { "user_id", session.UserId }
            };
            var _ = _client.RpcAsync(session, "clientrpc.send_notification", payload.ToJson());

            var result = await completer.Task;

            Assert.NotNull(result);
            Assert.Equal(session.UserId, result.SenderId);
        }
Beispiel #23
0
    // +++ unity lifecycle ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    async void Start()
    {
        // register ui events
        _ui.OnCreateMatch += OnUiCreateMatch;
        _ui.OnJoinMatch   += OnUiJoinMatch;
        _ui.OnStartGame   += OnStartGame;

        // start nakama client
        _client = new Client("defaultkey", _host, _port, false);

        // const string email = "*****@*****.**";
        // const string password = "******";
        // _session = await _client.AuthenticateEmailAsync(email, password);
        _session = await _client.AuthenticateDeviceAsync(System.Guid.NewGuid().ToString());

        Debug.LogFormat("Authenticated session: {0}", _session);
        Debug.Log(_session.AuthToken); // raw JWT token
        Debug.LogFormat("User id '{0}'", _session.UserId);
        Debug.LogFormat("User username '{0}'", _session.Username);
        Debug.LogFormat("Session has expired: {0}", _session.IsExpired);
        Debug.LogFormat("Session expires at: {0}", _session.ExpireTime); // in seconds.

        _account = await _client.GetAccountAsync(_session);

        Debug.LogFormat("User id '{0}'", _account.User.Id);
        Debug.LogFormat("User username '{0}'", _account.User.Username);
        Debug.LogFormat("Account virtual wallet '{0}'", _account.Wallet);

        _socket                      = _client.CreateWebSocket();
        _socket.OnConnect           += _socket_OnConnect;
        _socket.OnDisconnect        += _socket_OnDisconnect;
        _socket.OnChannelMessage    += _socket_OnChannelMessage;
        _socket.OnChannelPresence   += _socket_OnChannelPresence;
        _socket.OnError             += _socket_OnError;
        _socket.OnMatchmakerMatched += _socket_OnMatchmakerMatched;
        _socket.OnMatchPresence     += _socket_OnMatchPresence;
        _socket.OnMatchState        += _socket_OnMatchState;
        _socket.OnNotification      += _socket_OnNotification;
        _socket.OnStatusPresence    += _socket_OnStatusPresence;
        _socket.OnStreamPresence    += _socket_OnStreamPresence;
        _socket.OnStreamState       += _socket_OnStreamState;
        await _socket.ConnectAsync(_session);
    }
        public Task StartAsync()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(MessageDispatcher));
            }

            if (_currentState != States.Stopped)
            {
                throw new MessageDispatcherException("Dispatcher is not stopped!");
            }

            Task socketConnectTask = Task.Run(async() =>
            {
                _currentState = States.Starting;

                try
                {
                    await _socket.ConnectAsync();
                }
                catch
                {
                    _currentState = States.Stopped;
                    throw;
                }

                _currentState = States.Started;
            });

            _receivingTask = socketConnectTask.ContinueWith(async(socketTask) =>
            {
                while (_socket.IsConnected && _currentState == States.Started)
                {
                    byte[] buffer = await _socket.ReceiveAsync();

                    JObject message = _serializer.Deserialize(buffer);

                    MessageReceived?.Invoke(this, new RosbridgeMessageReceivedEventArgs(message));
                }
            });

            return(socketConnectTask);
        }
Beispiel #25
0
        public async void Login()
        {
            int port = DEFAULT_GATEWAY_PORT;

            if (!Int32.TryParse(_portInputField.text, out port))
            {
                _failedNotification.SetActive(true);
                return;
            }

            _client = new Client(SERVER_KEY, _serverInputField.text, port, false);

            // TODO there is actually a server-managed server field that currently holds a random string, we should update that:
            _username = _usernameInputField.text;
            try {
                _session = await _client.AuthenticateEmailAsync(
                    _username + FAKE_EMAIL_SUFFIX,
                    _passwordInputField.text);
            } catch {
                _failedNotification.SetActive(true);
                return;
            }

            _loginModal.SetActive(false);

            // TODO move everything below this line to a chat-management module?:
            _chatSocket = _client.CreateWebSocket();
            await _chatSocket.ConnectAsync(_session);

            _chatChannel = await _chatSocket.JoinChatAsync(
                CHAT_ROOM, ChannelType.Room, CHAT_ROOM_PERSISTENT, CHAT_ROOM_HIDDEN);

            _chatMessagesArea.text += $"Welcome {_username}, you have connected with session {_session} to {_chatChannel.Id}.\n";

            // Handle any incoming messages:
            _chatSocket.OnChannelMessage += (_, message) => {
                if (_chatChannel.Id == message.ChannelId)
                {
                    // TODO This is naive, we can't strongly type network input so directly..
                    _chatMessagesArea.text += message.Content.FromJson <ChatMessage>().Flatten();
                }
            };
        }
    // Start is called before the first frame update
    async void Start()
    {
        deviceId = SystemInfo.deviceUniqueIdentifier;
        Dictionary <string, string> authParams = new Dictionary <string, string>();

        authParams.Add("skillz_match_token", "1234567890");

        var session = await client.AuthenticateCustomAsync(deviceId, "test-client-2", false, authParams);

        //var session = await client.AuthenticateDeviceAsync(deviceId, "test-client-2", false);

        Debug.Log("Device authenticated with token:");
        Debug.Log(session.AuthToken); // raw JWT token
        Debug.LogFormat("Session user id: '{0}'", session.UserId);
        Debug.LogFormat("Session user username: '******'", session.Username);
        Debug.LogFormat("Session has expired: {0}", session.IsExpired);
        Debug.LogFormat("Session expires at: {0}", session.ExpireTime); // in seconds.

        socket = client.NewSocket();

        socket.Connected          += () => Debug.Log("Socket Connected");
        socket.Closed             += () => Debug.Log("Socket Closed");
        socket.ReceivedMatchState += ReceiveMatchStateMessage;

        await socket.ConnectAsync(session);



        //var match = await socket.CreateMatchAsync();
        //Debug.LogFormat("New match with id '{0}'.", match.Id);
        //var matchId = "01234567890123456789.nakama";

        var resp = await socket.RpcAsync("create_skillz_match", "{\"match_id\": \"01234567890123456789.nakama\"}");

        GameMsg gMsg = JsonUtility.FromJson <GameMsg>(resp.Payload);

        Debug.LogFormat("New Match ID: {0}", gMsg.match_id);

        serverMatchId = gMsg.match_id;
        var match = await socket.JoinMatchAsync(serverMatchId);
    }
Beispiel #27
0
        public async void Connect()
        {
            try
            {
                const string scheme    = "http";
                string       host      = serverText.text;
                int          port      = Int32.Parse(serverPortText.text);
                const string serverKey = "defaultkey";

                _client                = new Client(scheme, host, port, serverKey, UnityWebRequestAdapter.Instance);
                _socket                = _client.NewSocket();
                _socket.Closed        += () => Log("Socket closed.");
                _socket.Connected     += () => Log("Socket connected.");
                _socket.ReceivedError += e => Log("Socket error: " + e.Message);

                // Cant use SystemInfo.deviceUniqueIdentifier with WebGL builds.
                var udid = PlayerPrefs.GetString(UdidKey, Guid.NewGuid().ToString());
                Log("Unique Device ID: " + udid);

                ISession session;
                var      sessionToken = PlayerPrefs.GetString(SessionTokenKey);
                if (string.IsNullOrEmpty(sessionToken) || (session = Session.Restore(sessionToken)).IsExpired)
                {
                    Log("Before session");
                    session = await _client.AuthenticateDeviceAsync(udid);

                    PlayerPrefs.SetString(UdidKey, udid);
                    PlayerPrefs.SetString(SessionTokenKey, session.AuthToken);
                    Log("After session");
                }

                Log("Session Token: " + session.AuthToken);
                await _socket.ConnectAsync(session, true);

                Log("After socket connected.");
            }
            catch (Exception e)
            {
                Log(e.ToString());
            }
        }
Beispiel #28
0
        public static async Task <SocketError> ConnectAsync(this ISocket socket, SocketAwaitable awaitable)
        {
            Requires.NotNull(awaitable, nameof(awaitable));

            try
            {
                awaitable.Reset();

                if (!socket.ConnectAsync(awaitable.EventArgs))
                {
                    awaitable.CompleteSynchronously();
                }

                await awaitable;
                return(awaitable.EventArgs.SocketError);
            }
            catch (ObjectDisposedException)
            {
                return(SocketError.ConnectionAborted);
            }
        }
    // +++ 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));
    }
Beispiel #30
0
        protected override void DoInitialize()
        {
            var uri  = new Uri(Address);
            var args = new MySocketAsyncEventArgs();

            args.RemoteEndPoint = ParseEndpointAddress(new Uri(Address), AddressFamily);
            args.Completed     += _socketOperationCompleted;
            args.UserToken      = null;

            _socket = CreateSocket(uri.Host, args.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            base.BeginInitialize();

            bool asyncOperation = false;

            try
            {
                asyncOperation = _socket.ConnectAsync(args);
            }
            catch (SocketException ex)
            {
                args.SocketError = ex.SocketErrorCode;
            }
            catch (Exception ex)
            {
                if (ex.InnerException is SocketException socketException)
                {
                    args.SocketError = socketException.SocketErrorCode;
                }
                else
                {
                    args.SocketError = SocketError.OperationAborted;
                }
            }

            if (!asyncOperation)
            {
                SocketOperationCompleted(_socket, args);
            }
        }
        protected override void DoInitialize()
        {
            var args = new MySocketAsyncEventArgs();
            args.RemoteEndPoint = ParseEndpointAddress(new Uri(Address), AddressFamily);
            args.Completed += SocketOperationCompleted;
            args.UserToken = null;

            socket = CreateSocket(args.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            asyncOperationInProgress = true;

            if (!socket.ConnectAsync(args))
            {
                SocketOperationCompleted(socket, args);
            }
        }