public Chat(HubConnection connection) { _chat = connection.CreateProxy("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); } }); }
public JabbRClient(string url, IClientTransport transport) { _url = url; _connection = new HubConnection(url); _chat = _connection.CreateProxy("JabbR.Chat"); _clientTransport = transport ?? new AutoTransport(); }
static void StartClient() { var hub = new HubConnection("http://localhost:49899/"); var proxy = hub.CreateProxy("LivePricingHub"); proxy.On("TradeOccurred", d => { Console.WriteLine("UPDATE: {0} - {1:C} ({2:N0})", d.ShortCode, d.LastTradePrice, d.TradeVolume); }); hub.Start() .ContinueWith(t => { count++; for (int x = 0; x < 20; x++) { var listenTask = proxy.Invoke<dynamic>("ListenForPriceChanges", string.Format("Share {0}", x)); listenTask.ContinueWith(priceTask => { var price = priceTask.Result; }, TaskContinuationOptions.OnlyOnRanToCompletion); } Console.WriteLine("{0} Connected", count); }, TaskContinuationOptions.OnlyOnRanToCompletion); }
private async void Go() { var hubConnection = new HubConnection("http://localhost:1235/"); var hub = hubConnection.CreateProxy("moveShape"); hub.On<string, double, double>("shapeMoved", (cid, x, y) => { if (hubConnection.ConnectionId != cid) { 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)); }); }
public MainPage() { InitializeComponent(); textBlockMessages.Dispatcher.BeginInvoke(new Action(() => textBlockMessages.Text = "This program, SignalRWp7, begins\n")); hubConnection = new HubConnection("http://localhost:49522/"); hubConnection.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}", hubConnection.ConnectionId); // Do more stuff here } }); hubConnection.Received += data => { HubBub deserializedHubBub = JsonConvert.DeserializeObject<HubBub>(data); var args0 = deserializedHubBub.Args[0]; UpdateMessages(args0); }; chatHub = hubConnection.CreateProxy("Chat"); }
public Bot(string url, string name, string password) { Name = name; _password = password; _connection = new HubConnection(url); _chat = _connection.CreateProxy("JabbR.Chat"); }
public DynamicHubProxyInterceptor(HubConnection connection, Type type) { _type = type; var name = type.Name.Substring(1); _proxy = connection.CreateProxy(name); _connection = connection; _genericInvokeMethod = _proxy.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(m => m.Name == "Invoke" && m.ContainsGenericParameters).SingleOrDefault(); }
static void Main(string[] args) { var hubConnection = new HubConnection("http://localhost:8081/"); var ddpStream = hubConnection.CreateProxy("DDPStream"); ddpStream.On("flush", message => System.Console.WriteLine(message.prodName)); hubConnection.Start().Wait(); ddpStream.Invoke("Subscribe", "allproducts","product"); System.Console.Read(); }
static void Main(string[] args) { //輸入識別名稱 Console.Write("Please input client name: "); string clientName = Console.ReadLine(); //連線SignalR Hub var connection = new HubConnection("http://localhost:4112/"); IHubProxy commHub = connection.CreateProxy("CommHub"); //顯示Hub傳入的文字訊息 commHub.On("ShowMessage", msg => Console.WriteLine(msg)); //利用done旗標決定程式中止 bool done = false; //當Hub要求執行Exit()時,將done設為true commHub.On("Exit", () => { done = true; }); //建立連線,連線建立完成後向Hub註冊識別名稱 connection.Start().ContinueWith(task => { if (!task.IsFaulted) //連線成功時呼叫Server端方法register() commHub.Invoke("register", clientName); else done = true; }); //維持程式執行迴圈 while (!done) { Thread.Sleep(100); } //主動結束連線 connection.Stop(); }
public void Stop() { //for some reason when the process is stoping all the private instances in the object are missing //need to create specificaly for shutdown _hubConnection = new HubConnection(url); _hubConnection.ConnectionId = bus.InputAddress.Queue; _monitor = _hubConnection.CreateProxy("MonitorHub"); _hubConnection.Start().Wait(); _monitor.Invoke("Deregister", new { Server = bus.InputAddress.Machine, Endpoint = bus.InputAddress.Queue }); _hubConnection.Stop(); }
public TaskHub() { string signalrService = "http://andyjmay.com/Apps/TaskR"; hubConnection = new HubConnection(signalrService); hubProxy = hubConnection.CreateProxy("TaskHub"); hubProxy.On<IEnumerable<Task>>("GotTasksForUser", tasks => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new GotTasksForUserEvent(tasks)))); hubProxy.On<string>("GotLogMessage", message => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new GotLogMessageEvent(message)))); hubProxy.On<Task>("AddedTask", task => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new AddedTaskEvent(task)))); hubProxy.On<Task>("UpdatedTask", task => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new UpdatedTaskEvent(task)))); hubProxy.On<Task>("DeletedTask", task => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new DeletedTaskEvent(task)))); hubProxy.On<Exception>("HandleException", exception => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new ExceptionEncounteredEvent(exception)))); Messenger.Default.Register<LoginEvent>(this, (e) => { Login(e.Username); }); Messenger.Default.Register<AddTaskEvent>(this, (e) => { AddTask(e.TaskToAdd); }); Messenger.Default.Register<UpdateTaskEvent>(this, (e) => { UpdateTask(e.TaskToUpdate); }); Messenger.Default.Register<DeleteTaskEvent>(this, (e) => { DeleteTask(e.TaskToDelete); }); hubConnection.Start().ContinueWith(task => { if (task.IsFaulted) { DispatcherHelper.UIDispatcher.BeginInvoke(new Action(() => Messenger.Default.Send(new Events.ExceptionEncounteredEvent(task.Exception)))); return; } if (task.IsCompleted) { DispatcherHelper.UIDispatcher.BeginInvoke(new Action(() => { Messenger.Default.Send(new ConnectedToHubEvent()); //Messenger.Default.Send(new LoginEvent("andyjmay")); //var loginWindow = new LoginView(); //loginWindow.Closed += (sender, ev) => //{ // LoginView loginView = (LoginView)sender; // bool? result = loginView.DialogResult; // if (result.HasValue && result.Value == true) // { // Messenger.Default.Send(new LoginEvent(loginView.Username)); // } //}; //loginWindow.ShowDialog(); })); } }); }
public TorshifySongPlayerClient(Uri serverUri) { _connection = new HubConnection(serverUri.AbsoluteUri); _proxy = _connection.CreateProxy("TorshifyHub"); _proxy.On<ValueProgressEventArgs<int>>("Progress", OnProgress); _proxy.On<ValueProgressEventArgs<int>>("Buffering", OnBuffering); _proxy.On<ValueChangedEventArgs<float>>("VolumeChanged", OnVolumeChanged); _proxy.On<ValueChangedEventArgs<bool>>("IsMutedChanged", OnIsMutedChanged); _proxy.On<ValueChangedEventArgs<bool>>("IsPlayingChanged", OnIsPlayingChanged); _proxy.On<ValueChangedEventArgs<Song>>("CurrentSongChanged", OnCurrentSongChanged); _proxy.On<SongEventArgs>("CurrentSongCompleted", OnCurrentSongCompleted); }
static void Main(string[] args) { var connection = new HubConnection("http://localhost:9616/"); SignalRConsole.SignalR.MessengerHub.Message message = new SignalR.MessengerHub.Message(); message.Content = "Moo"; message.Duration = 500; message.Title = "Hello Title"; var myHub = connection.CreateProxy("messenger"); connection.Start().Wait(); Object[] myData = { (Object)message, "sourcing" }; myHub.Invoke("broadCastMessage", myData); }
public virtual void Init(TextWriter log) { this.log = log; secret = ConfigurationManager.AppSettings["TwitterCustomerSecret"]; while (streamingHubConnectAttempts++ < 3) { if (streamingHubConnectAttempts > 1) System.Threading.Thread.Sleep(5000); log.WriteLine("{0}: Attempting To Connect To PushURL '{1}' (Attempt: {2})", DateTime.Now, ConfigurationManager.AppSettings["PushURL"], streamingHubConnectAttempts); hubConnection = (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["PushURL"])) ? new HubConnection(ConfigurationManager.AppSettings["PushURL"]) : null; if (hubConnection != null) { try { streamingHub = hubConnection.CreateProxy("streamingHub"); hubConnection.StateChanged += new Action<SignalR.Client.StateChange>(sc => { if (sc.NewState == SignalR.Client.ConnectionState.Connected) { log.WriteLine("{0}: Push Connection Established", DateTime.Now); lock (queue_push_lock) { if (queue_push.Count > 0) { log.WriteLine("{0}: Pushing {1} Tweets to Web Application", DateTime.Now, queue_push.Count()); streamingHub.Invoke("Send", new StreamItem() { Secret = secret, Data = queue_push }).Wait(); queue_push.Clear(); } } } else if (sc.NewState == SignalR.Client.ConnectionState.Disconnected) log.WriteLine("{0}: Push Connection Lost", DateTime.Now); else if (sc.NewState == SignalR.Client.ConnectionState.Reconnecting) log.WriteLine("{0}: Reestablishing Push Connection", DateTime.Now); else if (sc.NewState == SignalR.Client.ConnectionState.Connecting) log.WriteLine("{0}: Establishing Push Connection", DateTime.Now); }); var startHubTask = hubConnection.Start(); startHubTask.Wait(); if (!startHubTask.IsFaulted) break; } catch (Exception ex) { hubConnection = null; log.WriteLine("{0}: Error: {1}", DateTime.Now, ex.ToString()); } } } }
public ActionResult Broadcast() { var conn = new HubConnection(Queue_Demo.Settings.hubUrl); var hub = conn.CreateProxy("queue"); var waitTime = "1000"; conn.Start().Wait(); hub.Invoke("ReportAverageWait", new object[] { waitTime }); return new EmptyResult(); }
static void Main(string[] args) { // AWS: Get instance public address string myId = "localhost"; try { myId = Encoding.ASCII.GetString(new WebClient().DownloadData("http://169.254.169.254/latest/meta-data/public-hostname")); } catch { } // AWS SQS Client var sqsClient = new AmazonSQSClient(); while (true) { // Get the next message ReceiveMessageRequest request = new ReceiveMessageRequest() .WithQueueUrl("https://queue.amazonaws.com/*****/codeCampDemo") .WithMaxNumberOfMessages(1); var response = sqsClient.ReceiveMessage(request); foreach (var retrievedMessage in response.ReceiveMessageResult.Message) { var messageJson = JsonValue.Parse(retrievedMessage.Body); var message = messageJson["message"].ReadAs<string>(); Console.WriteLine(message); message = "Echo: " + message; string address = string.Format("http://{0}", messageJson["sender"].ReadAs<string>()); var connection = new HubConnection(address); connection.Start().Wait(); IHubProxy pongHub = connection.CreateProxy("MvcWebRole1.Hubs.EchoHub"); pongHub.Invoke("DoUpdateMessage", message, myId).Wait(); //Process the message and then delete the message DeleteMessageRequest deleteRequest = new DeleteMessageRequest() .WithQueueUrl("https://queue.amazonaws.com/******/codeCampDemo") .WithReceiptHandle(retrievedMessage.ReceiptHandle); sqsClient.DeleteMessage(deleteRequest); } Thread.Sleep(1000); } }
public MainWindow() { InitializeComponent(); chatItems = new ObservableCollection<dynamic>(); ChatResults.ItemsSource = chatItems; cn = new HubConnection("http://localhost:5687/"); proxy = cn.CreateProxy("Chat"); proxy.On("AddMessage", message => Dispatcher.Invoke(new Action(() => chatItems.Add(message)))); cn.Start(); }
private void StartHubConnection() { hubConnection = new HubConnection("http://openpanel.apphb.com"); var topicHub = hubConnection.CreateProxy("topicHub"); topicHub.On<int, int, int>("voteUpdated", (answerId, topicId, vote) => { if (Topic.Id == topicId) { InvokeOnMainThread(() => { UpdateVoteCount(answerId, vote); }); } }); hubConnection.Start(); }
public ConnectionManager(IDispatcher dispatcher) { _dispatcher = dispatcher; var hub = new HubConnection("http://signallines.apphb.com"); _gameHub = hub.CreateProxy("GameHub"); _gameHub.On("addMessage", ProcessMessage); _gameHub.On<int, int, int>("lineClicked", HandleLineClicked); _gameHub.On<Player>("newPlayerJoined", ProcessNewPlayerJoined); _gameHub.On<GameState>("resetGame", HandleResetGame); _gameHub.On<Player>("playerLeft", HandlePlayerLeft); hub.Start().Wait(); }
static void Main(string[] args) { var connection = new HubConnection("http://localhost/WebApplication2/"); var hub = connection.CreateProxy("Chat"); hub.On<string>("AddMessage", Console.WriteLine); connection.Start().ContinueWith(t => { hub.Invoke("Send", "Hello there from command line"); }); Console.ReadLine(); }
public void Start() { string url = "http://localhost:8999/"; var connection = new HubConnection(url); IHubProxy serverHub = connection.CreateProxy(typeof (ServerHub).GetHubName()); serverHub.On("foo", () => Console.WriteLine("notified!")); serverHub.On("foo", s => Console.WriteLine(s)); startConnection(connection); serverHub.Invoke("SendMessage", "hello from Console Client").Wait(); }
static void Main(string[] args) { var hubConn = new HubConnection("http://localhost:7458/"); hubConn.Credentials = CredentialCache.DefaultNetworkCredentials; var msg = new NiCris.Web.ConsoleTester.Models.Message(); msg.Content = "Moo"; msg.Duration = 500; msg.Title = "Hello Title"; var hub = hubConn.CreateProxy("messenger"); hubConn.Start().Wait(); Object[] myData = { (Object)msg, "sourcing" }; hub.Invoke("broadCastMessage", myData); }
public void Start() { log4net.Config.XmlConfigurator.Configure(); string url = "http://localhost:63141/"; var connection = new HubConnection(url); IHubProxy loggerHub = connection.CreateProxy(typeof(SignalrConsoleAppenderHub).GetHubName()); SignalrConsoleAppender.Instance.Hub = loggerHub; startConnection(connection); Thread.Sleep(10000); LogManager.GetLogger("TheLogger").Info("from console app logger"); }
public void TestSendMessage() { var are = new System.Threading.AutoResetEvent(false); var connection = new SignalR.Client.Hubs.HubConnection("http://localhost:8081/"); var chatHub = connection.CreateProxy("chatHub_4"); connection.Start().ContinueWith(action => { if (action.IsFaulted) { Assert.Fail(string.Format("Error starting connection: {0}.", action.Exception.ToString())); } else Console.WriteLine("Connection started."); }).Wait(); bool addMessageExecuted = false; chatHub.On<WebApplication.ChatHub_4.MessageData>("AddMessage", (data) => { Assert.AreEqual("test name", data.UserName); Assert.AreEqual("hallo test world!", data.Message); addMessageExecuted = true; are.Set(); }); chatHub.Invoke("SendMessage", new { UserName = "******", Message = "hallo test world!" }).ContinueWith(task => { if (task.IsFaulted) Assert.Fail(string.Format("'SendMessage' invoke failed: {0}.", task.Exception.ToString())); else Console.WriteLine("'SendMessage' invoke completed."); }).Wait(); are.WaitOne(TimeSpan.FromSeconds(5)); Assert.IsTrue(addMessageExecuted); }
public void InitHub(string hubUri = "http://jabbr.net") { LogToUI ("Configuring for Jabbr host {0}", hubUri); _connection = new HubConnection(hubUri); _connection.Error += ConnectionOnError; _connection.Reconnected += ConnectionOnReconnected; _connection.Received += ConnectionOnReceived; _chat = _connection.CreateProxy("JabbR.Chat"); _chat.On<JabbrMessage, string>("addMessage", OnAddMessage); _chat.On<JabbrUser, string, bool>("addUser", OnAddUser); _chat.On<JabbrRooms>("logOn", OnLogOn); _chat.On<JabbrRoom>("joinRoom", OnJoinRoom); _chat.On<string, JabbrUser, string>("changeUserName", OnChangeUserName); _chat.On<string, string>("postNotification", OnPostNotification); _chat.On<JabbrRooms>("logOut", OnLogOut); _chat.On<JabbrUser>("showUserInfo", OnShowUserInfo); }
public ConnectionManager(Dispatcher dispatcher) { _dispatcher = dispatcher; var hub = new HubConnection("http://localhost:20449/"); _gameHub = hub.CreateProxy("GameHub"); _gameHub.On<string>("addMessage", ProcessMessage); _gameHub.On<int, int, int>("lineClicked", HandleLineClicked); _gameHub.On<Player>("newPlayerJoined", HandleNewPlayerJoined); _gameHub.On<GameState>("resetGame", HandleResetGame); _gameHub.On<Player>("playerLeft", HandlePlayerLeft); _gameHub.On<GameState>("addedToGame", HandleAddedToGame); hub.Start().ContinueWith(delegate { return IsReady = true; } ); }
public override void Run() { var client = new TwilioRestClient(Queue_Demo.Settings.accountSid, Queue_Demo.Settings.authToken); var queue = client.ListQueues().Queues.Where(q => q.FriendlyName == "Demo Queue").FirstOrDefault(); if (queue!=null) { var queueSid = queue.Sid; var conn = new HubConnection(Queue_Demo.Settings.hubUrl); var hub = conn.CreateProxy("Queue"); conn.Start(); while (true) { Thread.Sleep(10000); var waitTime = client.GetQueue(queueSid).AverageWaitTime; Debug.WriteLine(waitTime); hub.Invoke("ReportAverageWait", new object[] { waitTime }); } } }
private static void RunDemoHub(HubConnection hubConnection) { var demo = hubConnection.CreateProxy("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 => { Console.WriteLine(task.Exception); }, TaskContinuationOptions.OnlyOnFaulted); Task.Factory.StartNew(() => { Thread.Sleep(7000); hubConnection.Stop(); }); }
public ConnectionManager(Dispatcher dispatcher) { _dispatcher = dispatcher; #pragma warning disable 168 const string localUrl = "http://localhost:20449/"; const string remoteUrl = "http://192.168.10.42:8082/"; #pragma warning restore 168 var hub = new HubConnection(remoteUrl); _gameHub = hub.CreateProxy("GameHub"); _gameHub.On<string>("addMessage", ProcessMessage); _gameHub.On<int, int, int>("lineClicked", HandleLineClicked); _gameHub.On<Player>("newPlayerJoined", HandleNewPlayerJoined); _gameHub.On<GameState>("resetGame", HandleResetGame); _gameHub.On<Player>("playerLeft", HandlePlayerLeft); _gameHub.On<GameState>("addedToGame", HandleAddedToGame); hub.Start().ContinueWith(delegate { if (Started != null) _dispatcher.BeginInvoke(() => Started(this, new EventArgs())); } ); }
public static void Process() { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("QueueConnectionString")); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("buy-queue"); queue.CreateIfNotExist(); CloudQueueMessage retrievedMessage = queue.GetMessage(); if (retrievedMessage != null) { var item = JObject.Parse(retrievedMessage.AsString); Trace.WriteLine("Ordered: " + item["Name"], "Information"); var message = "Processed: " + item["Name"]; var instance = RoleEnvironment.CurrentRoleInstance.Role.Instances[0].Id; var connection = new HubConnection("http://" + item["Address"] + "/"); connection.Start().ContinueWith(t => { var processHub = connection.CreateProxy("MessagingHub"); processHub.Invoke("Processed", message, instance); }); queue.DeleteMessage(retrievedMessage); } }