private async Task RunHubConnectionAPI(string url) { var hubConnection = new HubConnection(url); hubConnection.TraceWriter = _traceWriter; var hubProxy = hubConnection.CreateHubProxy("HubConnectionAPI"); hubProxy.On<string>("displayMessage", (data) => hubConnection.TraceWriter.WriteLine(data)); await hubConnection.Start(); hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name); await hubProxy.Invoke("DisplayMessageCaller", "Hello Caller!"); string joinGroupResponse = await hubProxy.Invoke<string>("JoinGroup", hubConnection.ConnectionId, "CommonClientGroup"); hubConnection.TraceWriter.WriteLine("joinGroupResponse={0}", joinGroupResponse); await hubProxy.Invoke("DisplayMessageGroup", "CommonClientGroup", "Hello Group Members!"); string leaveGroupResponse = await hubProxy.Invoke<string>("LeaveGroup", hubConnection.ConnectionId, "CommonClientGroup"); hubConnection.TraceWriter.WriteLine("leaveGroupResponse={0}", leaveGroupResponse); await hubProxy.Invoke("DisplayMessageGroup", "CommonClientGroup", "Hello Group Members! (caller should not see this message)"); await hubProxy.Invoke("DisplayMessageCaller", "Hello Caller again!"); }
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); } }); }
static void Main(string[] args) { Console.Title = "SignalR Sample Windows Console Client"; HubConnection connection = new HubConnection("http://localhost:50991/"); IHubProxy hub = connection.CreateHubProxy("Echo"); connection.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("Failed to start: {0}", task.Exception.GetBaseException()); } else { Console.WriteLine("Success! Connected with client connection id {0}", connection.ConnectionId); // Do more stuff here } }); hub.Invoke<string>("Send", new { message = "Test" }).ContinueWith(task => { Console.WriteLine("Value from server {0}", task.Result); }); connection.Stop(); Console.ReadLine(); }
private async void Go() { var hubConnection = new HubConnection("http://localhost:1235/"); var hub = hubConnection.CreateHubProxy("moveShape"); hub.On<double, double>("shapeMoved", (x, y) => Dispatcher.InvokeAsync(() => { Canvas.SetLeft(Shape, (Body.ActualWidth - Shape.ActualWidth) * x); Canvas.SetTop(Shape, (Body.ActualHeight - Shape.ActualHeight) * y); }) ); hub.On<int>("clientCountChanged", count => Dispatcher.InvokeAsync(() => ClientCount.Text = count.ToString())); await hubConnection.Start(); Shape.Draggable((left, top) => hub.Invoke("MoveShape", left / (Body.ActualWidth - Shape.ActualWidth), top / (Body.ActualHeight - Shape.ActualHeight)) ); Closing += (_, __) => hubConnection.Stop(); }
public override void Run() { // This is a sample worker implementation. Replace with your logic. Trace.WriteLine("BackgroundService entry point called", "Information"); // Connect to SignalR var connection = new HubConnection(CloudConfigurationManager.GetSetting("ApiBaseUrl")); var proxy = connection.CreateHubProxy("Notifier"); connection.Start().Wait(); while (true) { Thread.Sleep(5000); var service = new VideoService(); Trace.WriteLine("Getting Media Services active jobs", "Information"); var activeJobs = service.GetActiveJobs(); foreach (var video in activeJobs.ToList()) { proxy.Invoke( "VideoUpdated", (video.JobStatus == JobStatus.Completed) ? service.Publish(video.Id) : video); } } }
public ShellViewModel() { _hubConnection = new HubConnection("http://localhost:52029/"); _gameHub = _hubConnection.CreateHubProxy("ScattergoramentHub"); _gameHub.On<char, DateTime>("gameStart", GameStart); _gameHub.On<string, DateTime>("gameEnd", GameEnd); _gameHub.On<bool, char, DateTime>("gameStatus", GameStatus); _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromMilliseconds(100); _timer.Tick += _timer_Tick; _timer.Start(); _hubConnection.Start() .ContinueWith(task=> { if (task.IsFaulted) { Console.WriteLine("An error occurred during the method call {0}", task.Exception.GetBaseException()); } else { RegisterPlayer(); } } ); }
// Constructor public MainPage() { InitializeComponent(); DataContext = App.ViewModel; var hubConnection = new HubConnection("http://192.168.2.128:50188"); chat = hubConnection.CreateHubProxy("chat"); chat.On<string>("newMessage", msg => Dispatcher.BeginInvoke(() => App.ViewModel.Items.Add(new ItemViewModel { LineOne = msg }))); hubConnection.Error += ex => Dispatcher.BeginInvoke(() => { var aggEx = (AggregateException)ex; App.ViewModel.Items.Add(new ItemViewModel { LineOne = aggEx.InnerExceptions[0].Message }); }); var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); hubConnection.Start().ContinueWith(task => { var ex = task.Exception.InnerExceptions[0]; App.ViewModel.Items.Add(new ItemViewModel { LineOne = ex.Message }); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, scheduler); }
public static void Main(string[] args) { Console.WriteLine("Press key to start..."); Console.ReadKey(); // Connect to the service //var hubConnection = new HubConnection("http://localhost:8080/signalr"); var hubConnection = new HubConnection("http://ipv4.fiddler:8082/signalr"); // Create a proxy to the chat service var chat = hubConnection.CreateHubProxy("chat"); // Print the message when it comes in chat.On("addMessage", message => Console.WriteLine(message)); // Start the connection hubConnection.Start(new LongPollingTransport()).Wait(); string line = null; while ((line = Console.ReadLine()) != null) { // Send a message to the server chat.Invoke("Send3", line).ContinueWith(t => { Console.WriteLine("Invoke finished"); }); //chat.Invoke<string>("Send2", line).ContinueWith(t => //{ // Console.WriteLine("Return value: " + t.Result); //}); } }
public void EndToEndTest(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(); var hubConnection = new HubConnection(host.Url); IHubProxy proxy = hubConnection.CreateHubProxy("ChatHub"); var wh = new ManualResetEvent(false); proxy.On("addMessage", data => { Assert.Equal("hello", data); wh.Set(); }); hubConnection.Start(host.Transport).Wait(); proxy.InvokeWithTimeout("Send", "hello"); Assert.True(wh.WaitOne(TimeSpan.FromSeconds(10))); hubConnection.Stop(); } }
private void bnConnect_Click(object sender, EventArgs e) { var hubConnection = new HubConnection("http://localhost:50188"); chat = hubConnection.CreateHubProxy("chat"); chat.On<string>("newMessage", msg => messages.Invoke(new Action(() => messages.Items.Add(msg)))); hubConnection.Start().Wait(); }
private static void RunHeaderAuthSample(HubConnection hubConnection) { var authHub = hubConnection.CreateHubProxy("HeaderAuthHub"); hubConnection.Headers.Add("username", "john"); authHub.On("display", (msg) => Console.WriteLine(msg)); hubConnection.Start().Wait(); }
public GameplayScene(GraphicsDevice graphicsDevice) : base(graphicsDevice) { starfield = new Starfield(worldWidth, worldHeight, worldDepth); grid = new Grid(worldWidth, worldHeight); ShipManager = new ShipManager(); BulletManager = new BulletManager(); GameStateManager = new GameStateManager(); AddActor(ShipManager); AddActor(BulletManager); AddActor(starfield); AddActor(grid); #if DEBUG hubConnection = new HubConnection("http://localhost:29058"); #else hubConnection = new HubConnection("http://vectorarena.cloudapp.net"); #endif hubProxy = hubConnection.CreateHubProxy("gameHub"); hubProxy.On("Sync", data => Sync(data)); hubConnection.Start().ContinueWith(startTask => { hubProxy.Invoke<int>("AddPlayer").ContinueWith(invokeTask => { ShipManager.InitializePlayerShip(invokeTask.Result, hubProxy); Camera.TargetObject = ShipManager.PlayerShip; Camera.Position = new Vector3(ShipManager.PlayerShip.Position.X, ShipManager.PlayerShip.Position.Y, 500.0f); }); }); }
private static void RunDemoHub(HubConnection hubConnection) { var demo = hubConnection.CreateHubProxy("demo"); hubConnection.StateChanged += change => { Console.WriteLine(change.OldState + " => " + change.NewState); }; demo.On<int>("invoke", i => { int n = demo.GetValue<int>("index"); Console.WriteLine("{0} client state index -> {1}", i, n); }); hubConnection.Start().Wait(); demo.Invoke("multipleCalls").ContinueWith(task => { using (var error = task.Exception.GetError()) { Console.WriteLine(error); } }, TaskContinuationOptions.OnlyOnFaulted); Task.Factory.StartNew(() => { Thread.Sleep(7000); hubConnection.Stop(); }); }
static void Main(string[] args) { var server = new HubConnection("http://localhost:8001/"); var method = server.CreateHubProxy("kinect"); var sensor = Microsoft.Kinect.KinectSensor.KinectSensors.First(); try { server.Start().Wait(); sensor.SkeletonFrameReady += (sender, eventArgs) => { using (var frame = eventArgs.OpenSkeletonFrame()) { if (frame == null) return; var skeletons = new Skeleton[frame.SkeletonArrayLength]; frame.CopySkeletonDataTo(skeletons); var user = skeletons.FirstOrDefault(x => x.TrackingState == SkeletonTrackingState.Tracked); if (user == null) return; var m = user.Joints. Where(x => x.TrackingState == JointTrackingState.Tracked) .Select(s => { var c = sensor.CoordinateMapper.MapSkeletonPointToColorPoint(s.Position, ColorImageFormat.RgbResolution640x480Fps30); return new JointPosition { x = c.X, y = c.Y }; }).ToList(); Console.Write("."); method.Invoke("Send",m); } }; sensor.SkeletonStream.Enable(new TransformSmoothParameters() { Correction = 0.7f, JitterRadius = 0.1f, MaxDeviationRadius = 0.1f, Prediction = 0.7f, Smoothing = 0.8f }); sensor.Start(); Console.WriteLine("Started."); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.ReadLine(); } finally { sensor.Stop(); sensor.Dispose(); server.Stop(); } }
public void Start() { _connection = new HubConnection("http://localhost:27367/"); _job=_connection.CreateHubProxy("JobStatusHub"); _job.On("started",onStarted); _job.On("finished", onFinished); _connection.Start(); }
public void Start() { _connection = new HubConnection(_testswarmUrl); _job = _connection.CreateHubProxy("JobStatusHub"); _job.On("started", onStarted); _job.On("finished", onFinished); _connection.Start(); }
/// <summary> /// Constructor. Initializes hubconnection /// </summary> public ConsoleHub() { connection = new HubConnection(connectionUrl); hubProxy = connection.CreateHubProxy(hubName); connection.Start().Wait(); hubProxy.Invoke("Send", "Console", "Console connected to hub").Wait(); _hub = this; }
/// <summary> /// Constructor. Initializes hubconnection /// </summary> public GeoHub() { connection = new HubConnection(connectionUrl); hubProxy = connection.CreateHubProxy(hubName); connection.Start().Wait(); //hubProxy.Invoke("Send", "Info", "").Wait(); _hub = this; }
private async Task ConnectToTweetMaprAsync() { string url = "http://localhost:18066"; HubConnection conn = new HubConnection(url); IHubProxy tweetsHub = conn.CreateHubProxy("TwitterHub"); tweetsHub.On<Tweet>("broadcastTweet", ProcessTweet); await conn.Start(); await tweetsHub.Invoke("SubscribeToStreamGroup", "Global"); }
private void Connect() { string serviceUrl = Config.GetServiceLocation(); var connection = new HubConnection(serviceUrl); connection.Credentials = CredentialCache.DefaultNetworkCredentials; IHubProxy chat = connection.CreateHubProxy("ClientNotificationHub"); chat.On<Message>("Send", MessageReceived); connection.Start().Wait(); }
public static IDisposable BrodcastFromServer() { var host = new MemoryHost(); IHubContext context = null; host.Configure(app => { var config = new HubConfiguration() { Resolver = new DefaultDependencyResolver() }; app.MapHubs(config); var configuration = config.Resolver.Resolve<IConfigurationManager>(); // The below effectively sets the heartbeat interval to five seconds. configuration.KeepAlive = TimeSpan.FromSeconds(10); var connectionManager = config.Resolver.Resolve<IConnectionManager>(); context = connectionManager.GetHubContext("EchoHub"); }); var cancellationTokenSource = new CancellationTokenSource(); var thread = new Thread(() => { while (!cancellationTokenSource.IsCancellationRequested) { context.Clients.All.echo(); } }); thread.Start(); var connection = new Client.Hubs.HubConnection("http://foo"); var proxy = connection.CreateHubProxy("EchoHub"); try { connection.Start(host).Wait(); Thread.Sleep(1000); } finally { connection.Stop(); } return new DisposableAction(() => { cancellationTokenSource.Cancel(); thread.Join(); host.Dispose(); }); }
private static void BeginListening() { var conn = new HubConnection("http://localhost:3538/"); var hub = conn.CreateHubProxy("SendHub"); hub.On<string>("DisplayMessage", s => Console.Out.WriteLine(s)); conn.Start(); }
private async void Start() { var hubConnection = new HubConnection("http://localhost:50308/"); var chatHub = hubConnection.CreateHubProxy("chatHub"); chatHub.On<string>("sendMessage", (message) => Dispatcher.Invoke(DispatcherPriority.Normal, new Action<string>(AddMessage), message)); chatHub.On<string>("sendServerTime", (message) => Dispatcher.Invoke(DispatcherPriority.Normal, new Action<string>(AddServerTime), message)); await hubConnection.Start(); Send.Click += (sender, args) => chatHub.Invoke("Send", "WPF said:" + Message.Text); }
private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = bindingSource1; var hubConnection = new HubConnection("http://localhost:8080"); hubProxy = hubConnection.CreateHubProxy("monitor"); hubProxy.On<IEnumerable<Artist>>("refresh", action => GetData()); hubConnection.Start().Wait(); GetData(); }
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) { _conn = new HubConnection("http://localhost:62883"); _proxy = _conn.CreateHubProxy("KanbanHub"); _proxy.On("cardCreated", result => Dispatcher.Invoke(DispatcherPriority.Normal, new Action<dynamic>(data => { var lane = Lanes.Single(l => l.ID == (string)data.Lane); lane.Cards.Add(new Card {ID = data.ID, Content = data.Content, Lane = lane}); }), result)); _conn.Start().Wait(); }
public void UnableToCreateHubThrowsError(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(); var hubConnection = new HubConnection(host.Url); IHubProxy proxy = hubConnection.CreateHubProxy("MyHub2"); hubConnection.Start(host.Transport).Wait(); Assert.Throws<MissingMethodException>(() => proxy.Invoke("Send", "hello").Wait()); } }
public void UnableToCreateHubThrowsError() { using (var host = new MemoryHost()) { host.MapHubs(); var hubConnection = new HubConnection("http://fake"); IHubProxy proxy = hubConnection.CreateHubProxy("MyHub2"); hubConnection.Start(host).Wait(); Assert.Throws<MissingMethodException>(() => proxy.Invoke("Send", "hello").Wait()); } }
public async Task StartListening() { _connection = new HubConnection(Url); _proxy = _connection.CreateHubProxy("gallery"); _proxy.On<IList<string>>("newPhotosReceived", urls => { if (NewPhotosReceived != null) NewPhotosReceived.Invoke(this, urls); }); await _connection.Start(); }
static void Main(string[] args) { var hubConnection = new HubConnection("http://localhost:53748"); var chat = hubConnection.CreateHubProxy("ChatHub"); chat.On<string, string>("broadcastMessage", (name, message) => { Console.Write(name + ": "); Console.WriteLine(message); }); hubConnection.Start().Wait(); chat.Invoke("Notify", "Console app", hubConnection.ConnectionId); string msg = null; while ((msg = Console.ReadLine()) != null) { chat.Invoke("Send", "Console app", msg).Wait(); } }
private void connect_Click(object sender, EventArgs e) { var hubConnection = new HubConnection("http://localhost:8842/"); chat = hubConnection.CreateHubProxy("chat"); chat.On<string>("addMessage", msg => { listBox1.Invoke(new Action(() => listBox1.Items.Add(msg))); }); hubConnection.Start().Wait(); }