public async Task ServerConnectSignalR(string username, MatchBeginDto matchBeginDto, OnWorkDone<MatchBeginDto> onCompleted)
 {
     InitialiseHubConnection(username);
     Debug.Log("Connecting for server!");
     await _connection.ConnectAsync();
     Debug.Log("Connection Complete...");
     onCompleted?.Invoke(matchBeginDto);
 }
Esempio n. 2
0
        private void AddButtonClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hubText.Text))
            {
                MessageBox.Show(
                    "Пожалуйста, введите адрес хаба для подключения. Скорее всего, эту информацию вы сможете найти на сайте вашего провайдера либо на форуме техподдержки.",
                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                _hub = _dcProvider.Engine.Hubs.Add(hubText.Text, _client.Settings.Nickname);
            }
            catch (Exception)
            {
                MessageBox.Show("Попытка подключения не удалась. Проверьте введенный адрес.");
                return;
            }

            _hub.ConnectionStatusChanged += HubConnectionStatusChanged;
            _hub.ActiveStatusChanged     += HubActiveStatusChanged;

            addButton.Enabled = false;
            hubText.Enabled   = false;

            _hub.ConnectAsync();
        }
Esempio n. 3
0
        public static async Task MainAsync(string[] args)
        {
            var baseUrl = "http://localhost:5000/hubs";

            if (args.Length > 0)
            {
                baseUrl = args[0];
            }

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddConsole(LogLevel.Debug);
            var logger = loggerFactory.CreateLogger <Program>();

            using (var httpClient = new HttpClient(new LoggingMessageHandler(loggerFactory, new HttpClientHandler())))
                using (var pipelineFactory = new PipelineFactory())
                {
                    logger.LogInformation("Connecting to {0}", baseUrl);
                    var transport = new LongPollingTransport(httpClient, loggerFactory);
                    using (var connection = await HubConnection.ConnectAsync(new Uri(baseUrl), new JsonNetInvocationAdapter(), transport, httpClient, pipelineFactory, loggerFactory))
                    {
                        logger.LogInformation("Connected to {0}", baseUrl);

                        var cts = new CancellationTokenSource();
                        Console.CancelKeyPress += (sender, a) =>
                        {
                            a.Cancel = true;
                            logger.LogInformation("Stopping loops...");
                            cts.Cancel();
                        };

                        // Set up handler
                        connection.On("Send", new[] { typeof(string) }, a =>
                        {
                            var message = (string)a[0];
                            Console.WriteLine("RECEIVED: " + message);
                        });

                        while (!cts.Token.IsCancellationRequested)
                        {
                            var line = Console.ReadLine();
                            logger.LogInformation("Sending: {0}", line);

                            await connection.Invoke <object>("Send", line);
                        }
                    }
                }
        }
        void OnConnectButton()
        {
#if CSHARP_7_OR_LATER
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            try
            {
                MessagePack.Resolvers.StaticCompositeResolver.Instance.Register(
                    MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance,
                    MessagePack.Unity.UnityResolver.Instance,
                    //MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
                    //MessagePack.Resolvers.StandardResolver.Instance,
                    MessagePack.Resolvers.ContractlessStandardResolver.Instance
                    );

                var options = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(MessagePack.Resolvers.StaticCompositeResolver.Instance);
                MessagePack.MessagePackSerializer.DefaultOptions = options;
            }
            catch
            { }
#endif

            IProtocol protocol = null;
#if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
            protocol = new MessagePackCSharpProtocol();
#elif BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
            protocol = new MessagePackProtocol();
#else
            protocol = new JsonProtocol(new LitJsonEncoder());
#endif
            // Crete the HubConnection
            hub = new HubConnection(new Uri(this.sampleSelector.BaseURL + this._path), protocol);

            // Subscribe to hub events
            hub.OnError += Hub_OnError;

            hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));

            // Set up server callable functions
            hub.On("Send", (string arg) => AddText(string.Format("On '<color=green>Send</color>': '<color=yellow>{0}</color>'", arg)).AddLeftPadding(20));
            hub.On <Person>("Person", (person) => AddText(string.Format("On '<color=green>Person</color>': '<color=yellow>{0}</color>'", person)).AddLeftPadding(20));
            hub.On <Person, Person>("TwoPersons", (person1, person2) => AddText(string.Format("On '<color=green>TwoPersons</color>': '<color=yellow>{0}</color>', '<color=yellow>{1}</color>'", person1, person2)).AddLeftPadding(20));

            AddText("StartConnect called");

            SetButtons(false, false);

            // And finally start to connect to the server
            await hub.ConnectAsync();

            SetButtons(false, true);
            AddText(string.Format("Hub Connected with <color=green>{0}</color> transport using the <color=green>{1}</color> encoder.", hub.Transport.TransportType.ToString(), hub.Protocol.Name));

            // Call a server function with a string param. We expect no return value.
            await hub.SendAsync("Send", "my message");

            // Call a parameterless function. We expect a string return value.
            try
            {
                string result = await hub.InvokeAsync <string>("NoParam");

                AddText(string.Format("'<color=green>NoParam</color>' returned: '<color=yellow>{0}</color>'", result))
                .AddLeftPadding(20);
            }
            catch (Exception ex)
            {
                AddText(string.Format("'<color=green>NoParam</color>' error: '<color=red>{0}</color>'", ex.Message)).AddLeftPadding(20);
            }

            // Call a function on the server to add two numbers. OnSuccess will be called with the result and OnError if there's an error.
            var addResult = await hub.InvokeAsync <int>("Add", 10, 20);

            AddText(string.Format("'<color=green>Add(10, 20)</color>' returned: '<color=yellow>{0}</color>'", addResult)).AddLeftPadding(20);

            var nullabelTestResult = await hub.InvokeAsync <int?>("NullableTest", 10);

            AddText(string.Format("'<color=green>NullableTest(10)</color>' returned: '<color=yellow>{0}</color>'", nullabelTestResult)).AddLeftPadding(20);

            // Call a function that will return a Person object constructed from the function's parameters.
            var getPersonResult = await hub.InvokeAsync <Person>("GetPerson", "Mr. Smith", 26);

            AddText(string.Format("'<color=green>GetPerson(\"Mr. Smith\", 26)</color>' returned: '<color=yellow>{0}</color>'", getPersonResult)).AddLeftPadding(20);

            // To test errors/exceptions this call always throws an exception on the server side resulting in an OnError call.
            // OnError expected here!

            try
            {
                var singleResultFailureResult = await hub.InvokeAsync <int>("SingleResultFailure", 10, 20);

                AddText(string.Format("'<color=green>SingleResultFailure(10, 20)</color>' returned: '<color=yellow>{0}</color>'", singleResultFailureResult)).AddLeftPadding(20);
            }
            catch (Exception ex)
            {
                AddText(string.Format("'<color=green>SingleResultFailure(10, 20)</color>' error: '<color=red>{0}</color>'", ex.Message)).AddLeftPadding(20);
            }

            // This call demonstrates IEnumerable<> functions, result will be the yielded numbers.
            var batchedResult = await hub.InvokeAsync <int[]>("Batched", 10);

            AddText(string.Format("'<color=green>Batched(10)</color>' returned items: '<color=yellow>{0}</color>'", batchedResult.Length)).AddLeftPadding(20);

            // OnItem is called for a streaming request for every items returned by the server. OnSuccess will still be called with all the items.
            hub.GetDownStreamController <int>("ObservableCounter", 10, 1000)
            .OnItem(result => AddText(string.Format("'<color=green>ObservableCounter(10, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
            .OnSuccess(result => AddText("'<color=green>ObservableCounter(10, 1000)</color>' OnSuccess.").AddLeftPadding(20))
            .OnError(error => AddText(string.Format("'<color=green>ObservableCounter(10, 1000)</color>' error: '<color=red>{0}</color>'", error)).AddLeftPadding(20));

            // A stream request can be cancelled any time.
            var controller = hub.GetDownStreamController <int>("ChannelCounter", 10, 1000);

            controller.OnItem(result => AddText(string.Format("'<color=green>ChannelCounter(10, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
            .OnSuccess(result => AddText("'<color=green>ChannelCounter(10, 1000)</color>' OnSuccess.").AddLeftPadding(20))
            .OnError(error => AddText(string.Format("'<color=green>ChannelCounter(10, 1000)</color>' error: '<color=red>{0}</color>'", error)).AddLeftPadding(20));

            // a stream can be cancelled by calling the controller's Cancel method
            controller.Cancel();

            // This call will stream strongly typed objects
            hub.GetDownStreamController <Person>("GetRandomPersons", 20, 2000)
            .OnItem(result => AddText(string.Format("'<color=green>GetRandomPersons(20, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
            .OnSuccess(result => AddText("'<color=green>GetRandomPersons(20, 1000)</color>' OnSuccess.").AddLeftPadding(20));
#endif
        }
Esempio n. 5
0
    //I use event functions because awaiting returns hubconn and this is useless
    public void ConnectToServer(string fbigToken        = null, string huaweiAuthCode = null,
                                string facebookAccToken = null, string name           = null, string pictureUrl = null,
                                bool demo = false)
    {
        Debug.Log("connecting to server");

        var query = HttpUtility.ParseQueryString(string.Empty);

        if (facebookAccToken != null)
        {
            query["fb_access_token"] = facebookAccToken;
        }

        if (fbigToken != null)
        {
            query["access_token"] = fbigToken;
        }

        if (huaweiAuthCode != null)
        {
            query["huaweiAuthCode"] = huaweiAuthCode;
        }

        if (name != null)
        {
            query["name"] = name;
        }
        if (pictureUrl != null)
        {
            query["pictureUrl"] = pictureUrl;
        }

        if (demo)
        {
            query["demo"] = "1";
        }


        var uriBuilder = new UriBuilder(getAddress())
        {
            Query = query.ToString()
        };

        Debug.Log($"connecting with url {uriBuilder.ToString()}");

        var hubOptions = new HubOptions()
        {
            SkipNegotiation   = true,
            PreferedTransport = TransportTypes.WebSocket,
        };

        hubConnection = new HubConnection(uriBuilder.Uri, protocol, hubOptions)
        {
            ReconnectPolicy = myReconnectPolicy,
        };

        // AssignGeneralRpcs();

        //I don't have this term "authentication" despite I make token authentication
        // HubConnection.AuthenticationProvider = new DefaultAccessTokenAuthenticator(HubConnection);

        hubConnection.OnConnected    += OnConnected;
        hubConnection.OnError        += OnError;
        hubConnection.OnClosed       += OnClosed;
        hubConnection.OnMessage      += OnMessage;
        hubConnection.OnReconnecting += OnReconnecting;

        BlockingOperationManager.I.Forget(hubConnection.ConnectAsync().AsUniTask());
    }