• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Client.HubConnection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Microsoft.AspNet.SignalR.Client.HubConnection的典型用法代码示例。如果您正苦于以下问题:C# HubConnection类的具体用法?C# HubConnection怎么用?C# HubConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



HubConnection类属于Microsoft.AspNet.SignalR.Client命名空间,在下文中一共展示了HubConnection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ConnectToSignalR

        private async Task ConnectToSignalR()
        {
            hubConnection = new HubConnection(App.MobileService.ApplicationUri.AbsoluteUri);

            if (user != null)
            {
                hubConnection.Headers["x-zumo-auth"] = user.MobileServiceAuthenticationToken;
            }
            else
            {
                hubConnection.Headers["x-zumo-application"] = App.MobileService.ApplicationKey;
            }

            proxy = hubConnection.CreateHubProxy("ChatHub");
            await hubConnection.Start();

            proxy.On<string>("helloMessage", async (msg) =>
             {
                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                 {
                     message += " " + msg;
                     Message.Text = message;
                 });

             });
        }
开发者ID:Satur01,项目名称:DemoSignalR,代码行数:26,代码来源:MainPage.cs


示例2: SendToGroupFromOutsideOfHub

        public async Task SendToGroupFromOutsideOfHub()
        {
            using (var host = new MemoryHost())
            {
                IHubContext<IBasicClient> hubContext = null;
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    app.MapSignalR(configuration);
                    hubContext = configuration.Resolver.Resolve<IConnectionManager>().GetHubContext<SendToSome, IBasicClient>();
                });

                var connection1 = new HubConnection("http://foo/");

                using (connection1)
                {
                    var wh1 = new AsyncManualResetEvent(initialState: false);

                    var hub1 = connection1.CreateHubProxy("SendToSome");

                    await connection1.Start(host);

                    hub1.On("send", wh1.Set);

                    hubContext.Groups.Add(connection1.ConnectionId, "Foo").Wait();
                    hubContext.Clients.Group("Foo").send();

                    Assert.True(await wh1.WaitAsync(TimeSpan.FromSeconds(10)));
                }
            }
        }
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:35,代码来源:GetHubContextFacts.cs


示例3: Chat

        public Chat(HubConnection connection)
        {
            _chat = connection.CreateHubProxy("Chat");

            _chat.On<User>("markOnline", user =>
            {
                if (UserOnline != null)
                {
                    UserOnline(user);
                }
            });

            _chat.On<User>("markOffline", user =>
            {
                if (UserOffline != null)
                {
                    UserOffline(user);
                }
            });

            _chat.On<Message>("addMessage", message =>
            {
                if (Message != null)
                {
                    Message(message);
                }
            });
        }
开发者ID:xiurui12345,项目名称:MessengR,代码行数:28,代码来源:Chat.cs


示例4: RunDemo

        private async Task RunDemo(string url)
        {
            var hubConnection = new HubConnection(url);

            var querystringData = new Dictionary<string, string>();
            querystringData.Add("name", "primaveraServer");

            var connection = new HubConnection(url, querystringData);

            hubConnection.TraceWriter = _traceWriter;

            var hubProxy = hubConnection.CreateHubProxy("rhHub");
            hubProxy.On<string>("addChatMessage", (n) =>
            {
                //string n = hubProxy.GetValue<string>("index");
                hubConnection.TraceWriter.WriteLine("{0} ", n);
            });

            await hubConnection.Start();

            hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name);

            hubConnection.TraceWriter.WriteLine("Invoking long running hub method with progress...");
            await hubProxy.Invoke("SendChatMessage", new object[]   { "primaveraServer", "ola" });
            //hubConnection.TraceWriter.WriteLine("{0}", result);

            //await hubProxy.Invoke("multipleCalls");
        }
开发者ID:gmahota,项目名称:CRM_MIT,代码行数:28,代码来源:CommonClient.cs


示例5: ConnectToServer

        public void ConnectToServer()
        {

            hubConnection = new HubConnection(serverAddress);
            hubProxy = hubConnection.CreateHubProxy("SoftNodesHub");
            bool isConnected = false;
            while (!isConnected)
            {
                try
                {
                    hubConnection.Start().Wait();
                    hubConnection.Closed += OnHubConnectionClosed;
                    //hubProxy.On<Message>("ReceiveMessage", ReceiveMessage);

                    isConnected = true;
                    LogInfo("Connected to server");
                    OnConnected?.Invoke();
                }
                catch (Exception e)
                {
                    LogError("Connection to server failed: " + e.Message);
                    OnConnectionFailed?.Invoke(e.Message);
                }
            }
        }
开发者ID:nickpirrottina,项目名称:MyNetSensors,代码行数:25,代码来源:SoftNodeSignalRTransmitter.cs


示例6: OpenConnection

 public void OpenConnection()
 {
     _connection = new HubConnection(_hubUrl);
     _alertHubProxy = _connection.CreateHubProxy("alertHub");
     _resourceHubProxy = _connection.CreateHubProxy("resourceHub");
     _connection.Start().Wait();
 }
开发者ID:docrinehart,项目名称:deathstar-imperator,代码行数:7,代码来源:HubClient.cs


示例7: DisplayMenu

        //Data should be brought down from the SERVER, more specifically from the PLAYERLIST. Four slots, one for each of the four players.
        //If no data available, say N/A (Not Applicable)
        //If possible, display in order of score/health, so that pausing the game shows who's 'winning' or 'losing' at that time.

        public DisplayMenu(Texture2D bttnContinueSprite)
        {
            bttnContinue = new MenuButton(bttnContinueSprite, new Point(700, 570));
            HubConnection connection = new HubConnection("http://localhost:56859");
            proxy = connection.CreateHubProxy("UserInputHub");
            connection.Start().Wait();
        }
开发者ID:S00147430,项目名称:Casual-Games-Group-Assignment-2016,代码行数:11,代码来源:DisplayMenu.cs


示例8: Connect

		public async Task Connect(string uri)
		{
			var connection = new HubConnection(uri);
			connection.Closed += () =>
			{
				var eh = OnDisconnect;
				if (eh != null) eh();
			};
			var hubProxy = connection.CreateHubProxy("MyHub");
			hubProxy.On<string, string>("AddMessage", (userName, message) =>
			{
				var eh = On;
				if (eh != null) eh(userName, message);
			});
			try
			{
				await connection.Start();
			}
			catch (AggregateException e)
			{
				throw e.InnerException;
			}


			_connection = connection;
			_hubProxy = hubProxy;
		}
开发者ID:halllo,项目名称:MBus,代码行数:27,代码来源:MBusClient.cs


示例9: HubInitial

        public void HubInitial()
        {
            Connection = new HubConnection("http://54.69.68.144:8733/signalr");

            HubProxy = Connection.CreateHubProxy("ChatHub");

            HubProxy.On<string>("AddMessage",(msg) =>
                Device.BeginInvokeOnMainThread(() =>
                {
                   MessageService.AddMessage(msg,false,_controls);
                }));

            HubProxy.On<int>("GetNumberOfUsers", (count) =>
                Device.BeginInvokeOnMainThread(() =>
                {
                    MessageService.SetUsersCount(count, _controls);
                }));

            try
            {
                Connection.Start().Wait();
                Device.BeginInvokeOnMainThread(() =>
                {
                    _controls.ProgressBar.ProgressTo(.9, 250, Easing.Linear);
                });
            }
            catch (Exception e)
            {
                MessageTemplate.RenderError("Невозможно подключиться к серверу");
            }
            HubProxy.Invoke("GetNumberOfUsers");
        }
开发者ID:unrealdrake,项目名称:eChat,代码行数:32,代码来源:HubInitializer.cs


示例10: RunDemo

        private async Task RunDemo(string url)
        {
            cde = new CountdownEvent(invocations);
            ITaskAgent client = this;
            ITaskScheduler server = this;

            var hubConnection = new HubConnection(url);
            hubConnection.TraceWriter = _traceWriter;

            _hubProxy = hubConnection.CreateHubProxy("TaskSchedulerHub");            
            _hubProxy.On<TimeSpan>("RunSync", client.RunSync);
            _hubProxy.On<TimeSpan>("RunAsync", (data) => client.RunAsync(data));

            await hubConnection.Start(new LongPollingTransport());

            var smallDuration = TimeSpan.FromMilliseconds(500);
            var largeDuration = TimeSpan.FromSeconds(10);

            for (int i = 0; i < invocations; i++ )
            {
                server.AssignMeShortRunningTask(smallDuration);
                server.AssignMeLongRunningTask(largeDuration);
            }

            cde.Wait();
        }
开发者ID:haseebshujja,项目名称:Samples,代码行数:26,代码来源:HubTClient.cs


示例11: Start

        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;

            var uri = string.Format("http://*:{0}{1}", portNumber, siteUrl);

            const string url = "http://localhost:10000";
            StartOptions options = new StartOptions();
            options.Urls.Add(string.Format("http://{0}:10000", Environment.MachineName));
            options.Urls.Add("http://localhost:10000/");
            options.Urls.Add(uri);

            host = WebApp.Start<Startup>(options);

            var hubConnection = new HubConnection(url);
            var hubProxy = hubConnection.CreateHubProxy("MyHub");

            hubConnection.Start().ContinueWith(task =>
            {

            }).Wait();

            var timer = new Timer(x =>
            {
                if (ConnectionMapping.Count <= 1) return;

                hubProxy.Invoke("Send").Wait();
            }, null, 0, 2000);
        }
开发者ID:DeanMcgarrigle,项目名称:Predictor,代码行数:30,代码来源:WinService.cs


示例12: ConnectServer

 public void ConnectServer(string server, string port, string customerId, string accountId)
 {
     string ServerURI = server + ":" + port;
     //string ServerURI = "http://localhost:8080/";
     //if (Connection == null)
     Connection = new HubConnection(ServerURI);
     HubProxy = Connection.CreateHubProxy("ChatHub");
     try
     {
         Connection.Start().ContinueWith(task =>
         {
             if (task.IsFaulted)
             {
                 object[] obj = { false, "Can't connect to server." };
                 FireEvent("Login", obj);
             }
             else
             {
                 AuthenRequest(customerId, accountId);
             }
         });
     }
     catch (Exception ex)
     {
     }
 }
开发者ID:anhtv13,项目名称:ATDChatClient,代码行数:26,代码来源:DataManager.cs


示例13: MainWindow

        public MainWindow()
        {
            InitializeComponent();
            var hubConnection = new HubConnection("http://divewakeweb.azurewebsites.net/");
            stockTickerHubProxy = hubConnection.CreateHubProxy("WakeHub");
            hubConnection.Start().Wait();
            _sensor = KinectSensor.GetDefault();

            if (_sensor != null)
            {
                _sensor.Open();

                _bodies = new Body[_sensor.BodyFrameSource.BodyCount];

                _colorReader = _sensor.ColorFrameSource.OpenReader();
                _colorReader.FrameArrived += ColorReader_FrameArrived;
                _bodyReader = _sensor.BodyFrameSource.OpenReader();
                _bodyReader.FrameArrived += BodyReader_FrameArrived;

                // 2) Initialize the face source with the desired features
                _faceSource = new FaceFrameSource(_sensor, 0, FaceFrameFeatures.BoundingBoxInColorSpace |
                                                              FaceFrameFeatures.FaceEngagement |
                                                              FaceFrameFeatures.Glasses |
                                                              FaceFrameFeatures.LeftEyeClosed |
                                                              FaceFrameFeatures.PointsInColorSpace |
                                                              FaceFrameFeatures.RightEyeClosed);
                _faceReader = _faceSource.OpenReader();
                _faceReader.FrameArrived += FaceReader_FrameArrived;
            }
        }
开发者ID:supershirin,项目名称:DriveWake,代码行数:30,代码来源:MainWindow.xaml.cs


示例14: StartSignalRHubConnection

 private void StartSignalRHubConnection()
 {
     //TODO: Specify your SignalR website settings in SCPHost.exe.config
     this.hubConnection = new HubConnection(ConfigurationManager.AppSettings["SignalRWebsiteUrl"]);
     this.twitterHubProxy = hubConnection.CreateHubProxy(ConfigurationManager.AppSettings["SignalRHub"]);
     hubConnection.Start().Wait();
 }
开发者ID:juvchan,项目名称:AzureDataLake,代码行数:7,代码来源:SignalRBroadcastBolt.cs


示例15: Connect

        private async void Connect()
        {
            Connection = new HubConnection(ServerURI);
            HubProxy = Connection.CreateHubProxy("NotifierHub");

            HubProxy.On<AlarmMessage>("SendNotification", async (notification) =>
            {
                await this.AlarmsList.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    this.AlarmsList.Items.Add(notification);
                });
            }
            );

            try
            {
                await Connection.Start();
            }
            catch (HttpRequestException)
            {
                return;
            }
            catch (Exception)
            {
                return;
            }
        }
开发者ID:VivendoByte,项目名称:AlarmNotifier,代码行数:27,代码来源:MainPage.xaml.cs


示例16: CrestLogger

 public CrestLogger()
 {
     var hubConnection = new HubConnection("http://www.contoso.com/");
     errorLogHubProxy = hubConnection.CreateHubProxy("ErrorLogHub");
     //errorLogHubProxy.On<Error>("LogError", error => { });
     hubConnection.Start().Wait();
 }
开发者ID:calvaryccm,项目名称:Crest,代码行数:7,代码来源:CrestLogger.cs


示例17: OpenConnection

        private async Task OpenConnection()
        {
            var url = $"http://{await _serverFinder.GetServerAddressAsync()}/";

            try
            {
                _hubConnection = new HubConnection(url);

                _hubProxy = _hubConnection.CreateHubProxy("device");
                _hubProxy.On<string>("hello", message => Hello(message));
                _hubProxy.On("helloMsg", () => Hello("EMPTY"));
                _hubProxy.On<long, bool, bool>("binaryDeviceUpdated", (deviceId, success, binarySetting) => InvokeDeviceUpdated(deviceId, success, binarySetting: binarySetting));
                _hubProxy.On<long, bool, double>("continousDeviceUpdated", (deviceId, success, continousSetting) => InvokeDeviceUpdated(deviceId, success, continousSetting));

                await _hubConnection.Start();

                await _hubProxy.Invoke("helloMsg", "mobile device here");

                Debug.WriteLine($"{nameof(RealTimeService)}.{nameof(OpenConnection)} SignalR connection opened");
            }
            catch (Exception e)
            {
                Debug.WriteLine($"{nameof(RealTimeService)}.{nameof(OpenConnection)} ex: {e.GetType()}, msg: {e.Message}");
            }
        }
开发者ID:rwojcik,项目名称:imsClient,代码行数:25,代码来源:RealTimeService.cs


示例18: ListenerService

        public ListenerService()
        {
            InitializeComponent();
            
            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            EventLog.Log = "HubCollectorLog";
            StatsdClient = new Statsd(Config.Hostname, Config.Port);
            KlondikeConnections = new List<HubConnection>();

            Config.Hubs.ForEach(hub =>
            {
                var connection = new HubConnection(hub);

                IHubProxy statusHubProxy = connection.CreateHubProxy("status");
                statusHubProxy.On("updateStatus", status =>
                {
                    string name = Config.NameFromUrl(connection.Url);
                    var message = String.Format("From {2}: Status: {0}, Total: {1}", status.synchronizationState,
                        status.totalPackages, name);
                    EventLog.WriteEntry(message);
                    //Console.WriteLine(message);

                    StatsdClient.LogGauge("nuget."+ name +".packageCount", (int) status.totalPackages);
                });

                KlondikeConnections.Add(connection);
            });
        }
开发者ID:plukevdh,项目名称:signalr_service_demo,代码行数:28,代码来源:ListenerService.cs


示例19: Main

        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                var conHub = new HubConnection("http://localhost:8080/");
                conHub.CreateHubProxy("Shell").On<ShellCommandParams>("cmd", (data) =>
                {
                });

                using (var con = new Connection("http://localhost:8080/api/cmd"))
                {
                    con.Received += (data) =>
                    {
                        Console.WriteLine($"ola, recebi! {data}");
                    };
                    con.StateChanged += (state) =>
                    {
                        if (state.NewState != state.OldState)
                        {
                            Console.WriteLine($"De {state.OldState} para {state.NewState}");
                        }
                    };
                    await con.Start();

                    await con.Send("Hello Mello");
                }
            }).Wait();

        }
开发者ID:joaomello,项目名称:remote-terminal,代码行数:29,代码来源:Program.cs


示例20: Main

        //[STAThread]
        static void Main(string[] args)
        {
            HubConnection hub = new HubConnection("http://localhost:57365/");

            var prxy=hub.CreateHubProxy("RemoteHub");
            prxy.On<string, string>("commandReceived", (command, parameters) => {
                Console.WriteLine(string.Format("Command : {0}, Parameters : {1} ", command, parameters));
                if ("executecommand".Equals(command, StringComparison.OrdinalIgnoreCase))
                {
                    System.Diagnostics.Process.Start("CMD.exe", "/C " + parameters);
                }
            });
            hub.Start().Wait();

            //var config = new HttpSelfHostConfiguration("http://localhost:4521");
            //System.Threading.Thread.Sleep(5000);
            //config.Routes.MapHttpRoute(
            //    "API Default", "api/{controller}/{id}",
            //    new { id = RouteParameter.Optional });

            //using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            //{
            //    server.OpenAsync().Wait();
            //    Console.WriteLine("Press Enter to quit.");
            //    Console.ReadLine();
            //}
            Console.ReadLine();
        }
开发者ID:ishwormali,项目名称:practices,代码行数:29,代码来源:Program.cs



注:本文中的Microsoft.AspNet.SignalR.Client.HubConnection类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Hosting.HostContext类代码示例发布时间:2022-05-26
下一篇:
C# SignalR.HubConfiguration类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap