Esempio n. 1
4
        public void ConnectAsync()
        {
            Connection = new HubConnection("http://54.69.68.144:8733/signalr");
            HubProxy = Connection.CreateHubProxy("ChatHub");
            //Handle incoming event from server: use Invoke to write to console from SignalR's thread

            HubProxy.On<string>("AddMessage", (msg) =>
                    Console.WriteLine("AddMessage Call: " + msg)
            );
            HubProxy.On<string>("GetAllMessage", (s) =>
                    Console.WriteLine(String.Format("{0}: {1}", Environment.NewLine, s))
            );
            HubProxy.On<int>("GetNumberOfUsers",(s) =>
                Console.WriteLine(s)
            )
            ;
            try
            {
                Connection.Start().Wait();
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Unable to connect to server: Start server before connecting clients.");
            }

            //HubProxy.Invoke("GetAllMessages");
            //await HubProxy.Invoke("GetNumberOfUsers");
        }
Esempio n. 2
1
        /* Constructor for page */
        public MainPage()
        {
            // Initialize the component model
            InitializeComponent();

            // Set the data context for the page bindings
            DataContext = App.ViewModel;

            // Create speech recognizer 
            _Recognizer = new SpeechRecognizerUI();

            // Bind up shake gesture
            ShakeGesturesHelper.Instance.ShakeGesture += new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture);
            ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 4;
            ShakeGesturesHelper.Instance.Active = true;

            // Create demo recognizer and set grammer
            _DemoRecognizer = new SpeechRecognizerUI();
            _DemoRecognizer.Recognizer.Grammars.AddGrammarFromList("Demo", App.GrammerList);

            // Create speech synthesizer
            _Synthesizer = new SpeechSynthesizer();

            // Create signalr connection
            _Connection = new HubConnection("http://sagevoice.azurewebsites.net/");
            _Connection.StateChanged += change => ReportChange(change);

            // Create hub proxy
            _Hub = _Connection.CreateHubProxy("erpTicker");
            _Hub.On<string>("addResponse", data => OnResponse(data));
        }
Esempio n. 3
0
 // Constructor
 public MainPage()
 {
     _hubConnection = new HubConnection("http://signalrandiot.azurewebsites.net");
     _deviceHubProxy = _hubConnection.CreateHubProxy("DeviceDataHub");
     _deviceHubProxy.On<DeviceData>("NewDataRecieved", x =>
     {
         Dispatcher.BeginInvoke(() => 
         {
             if (x.DataType == "Temperature")
             {
                 ((ArrowGaugeIndicator)this.TempatureGauge.Indicators.Single(y => y.GetType() == typeof(ArrowGaugeIndicator))).Value = x.DataValue;
             }
             else if (x.DataType == "Humidity")
             {
                 ((ArrowGaugeIndicator)this.HumidityGauge.Indicators.Single(y => y.GetType() == typeof(ArrowGaugeIndicator))).Value = x.DataValue;
             }
             else if (x.DataType == "Light")
             {
                 ((ArrowGaugeIndicator)this.LightGauge.Indicators.Single(y => y.GetType() == typeof(ArrowGaugeIndicator))).Value = x.DataValue;
             }
             else if (x.DataType == "Distance")
             {
                 ((ArrowGaugeIndicator)this.DistanceGauge.Indicators.Single(y => y.GetType() == typeof(ArrowGaugeIndicator))).Value = x.DataValue;
             }
         });
         
     });
     InitializeComponent();
     this._hubConnection.Start();
 }
Esempio n. 4
0
        private void StartService()
        {
            try
            {

                if (_ProxyAuth != null)
                {
                    if (_ProxyAuth.Authenticated)
                    {
                        _Hub = new Microsoft.AspNet.SignalR.Client.HubConnection(RemoteDesktop_CSLibrary.Config.SignalRHubUrl);
                        _ProxyHub = _Hub.CreateHubProxy(RemoteDesktop_CSLibrary.Config.SignalRHubName);
                        _Hub.TransportConnectTimeout = new TimeSpan(0, 0, 4);
                        _ProxyHub.On<List<Client>>("AvailableClients", ReceivedClients);
                        _Hub.Error += _Hub_Error;
                        if (ProxyAuth.UsingWindowsAuth)
                        {
                            _Hub.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                        }
                        else
                        {
                            _Hub.CookieContainer = new CookieContainer();
                            _Hub.CookieContainer.Add(_ProxyAuth.AuthCookie);
                        }
                        _Hub.Start();
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Esempio n. 5
0
        private async void StartConnection()
        {
            // Connect to the server
            try
            {
                var hubConnection = new HubConnection("http://192.168.0.43:61893/");

                // Create a proxy to the 'ChatHub' SignalR Hub
                chatHubProxy = hubConnection.CreateHubProxy("ChatHub");

                // Wire up a handler for the 'UpdateChatMessage' for the server
                // to be called on our client
                chatHubProxy.On<string,string>("broadcastMessage", (name, message) => {
                    var str = $"{name}:{message}\n";
                RunOnUiThread(()=>     text.Append( str ) );
                });


                // Start the connection
                await hubConnection.Start();


            }
            catch (Exception e)
            {
                text.Text = e.Message;
            }
        }
Esempio n. 6
0
 public Bot(string url, string name, string password)
 {
     Name = name;
     _password = password;
     _connection = new HubConnection(url);
     _chat = _connection.CreateProxy("JabbR.Chat");
 }
Esempio n. 7
0
        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);
                }
            });
        }
Esempio n. 8
0
        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);
                });
            });
        }
        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);
                }
            }
        }
Esempio n. 10
0
File: Bot.cs Progetto: cmaish/jibbr
 public Bot(string url, string name, string password)
 {
     Name = name;
     _connection = new HubConnection(url);
     _connection.CookieContainer = this.BuildCookieContainer(url + "/account/login", name, password);
     _chat = _connection.CreateHubProxy("Chat");
 }
 public CoordinateHubClient(Action<Coordinate> callback)
 {
     _hubConnection = new HubConnection("http://indoorgps.azurewebsites.net");
     _hubProxy = _hubConnection.CreateHubProxy("CoordinateHub");
     _hubProxy.On<Coordinate>("SendNewCoordinate", callback);
     _hubConnection.Start().Wait();
 }
        public Client(string platform)
        {
            _platform = platform;

            _connection = new HubConnection("http://meetupsignalrxamarin.azurewebsites.net/");
            _proxy = _connection.CreateHubProxy("ChatHub");
        }
 private static void Connect()
 {
     analyticsWebsiteExceptionHubConnection = new HubConnection(analyticsWebsiteConnectionUrl);
     analyticsWebsiteProxy = analyticsWebsiteExceptionHubConnection.CreateHubProxy("ExceptionHub");
     analyticsWebsiteExceptionHubConnection.Start().Wait();
     analyticsWebsiteConnected = true;
 }
        //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();
        }
Esempio n. 15
0
 public void Dispose()
 {
     scheduler.Shutdown(true);
     scheduler = null;
     hubProxy = null;
     Logger.loggerInternal = (m) => { Console.WriteLine(m); };
 }
Esempio n. 16
0
        // 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);
        }
Esempio n. 17
0
        private static void Enviar(IHubProxy _hub, string nome)
        {
            var mensagem = Console.ReadLine();
            _hub.Invoke("Send", nome, mensagem).Wait();

            Enviar(_hub, nome);
        }
Esempio n. 18
0
        public App()
        {
            InitializeComponent();

            var label = new Label();
            var button = new Button()
            {
                Text = "送信",
            };

            conn = new HubConnection("http://localhost:5000");
            proxy = conn.CreateHubProxy("hello");

            proxy.On<string>("helloWorld", x => { label.Text = x; });
            conn.Start();

            button.Clicked += OnClick;

            var stack = new StackLayout()
            {
                Orientation = StackOrientation.Vertical,
            };
            stack.Children.Add(label);
            stack.Children.Add(button);

            MainPage = new ContentPage()
            {
                Content = stack,
            };
        }
Esempio n. 19
0
        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");
        }
Esempio n. 20
0
        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}");
            }
        }
Esempio n. 21
0
 public JabbRClient(string url, IClientTransport transport)
 {
     _url = url;
     _connection = new HubConnection(url);
     _chat = _connection.CreateProxy("JabbR.Chat");
     _clientTransport = transport ?? new AutoTransport();
 }
Esempio n. 22
0
		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;
		}
Esempio n. 23
0
 public void OpenConnection()
 {
     _connection = new HubConnection(_hubUrl);
     _alertHubProxy = _connection.CreateHubProxy("alertHub");
     _resourceHubProxy = _connection.CreateHubProxy("resourceHub");
     _connection.Start().Wait();
 }
partial         void Application_Initialize()
        {
            HubConnection hubConnection;
            http://localhost:49499
            hubConnection = new HubConnection("http://localhost:49499"); //make sure it matches your port in development

              //  HubProxy = hubConnection.CreateProxy("MyHub");
            HubProxy = hubConnection.CreateHubProxy("Chat");
            HubProxy.On<string, string>("CustomersInserted", (r, user) =>
            {
                this.ActiveScreens.First().Screen.Details.Dispatcher.BeginInvoke(delegate() {
                    this.ActiveScreens.First().Screen.ShowMessageBox("han creat un client");
                });
              //  this.Details.Dispatcher.BeginInvoke(() =>
              //  {
              //      this.ActiveScreens.First().Screen.ShowMessageBox("han creat un client");
              ////      Console.WriteLine("Han creat un client");
              //  });
            });

            HubProxy.On<string>("addMessage", (missatge) =>
            {
                this.ActiveScreens.First().Screen.Details.Dispatcher.BeginInvoke(delegate()
                {
                    this.ActiveScreens.First().Screen.ShowMessageBox("has rebut un "+missatge);
                });
                //  this.Details.Dispatcher.BeginInvoke(() =>
                //  {
                //      this.ActiveScreens.First().Screen.ShowMessageBox("han creat un client");
                ////      Console.WriteLine("Han creat un client");
                //  });
            });
            hubConnection.Start().Wait();
        }
Esempio n. 25
0
        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");
        }
Esempio n. 26
0
        /// <summary>
        /// Hubをセットする
        /// </summary>
        /// <param name="hub"></param>
        public void SetHub(IHubProxy hub)
        {
            if(hub == null) throw new ArgumentNullException(nameof(hub));
            this.hub = hub;
            
            hub.On<string, Type>("serve",async (json, type) =>
              {
                  var noodles = lib.NoodleListConverter.Convert(json, type);
                  if(!noodles.Any()) return;
                  
                  ServedInformation = string.Join("\r\n", ServedInformation, $"{noodles.First().Name}が流れてきたよ!");
                  _flowing = true;

                  try
                  {
                      await Task.Delay(5000);
                      if(!_isPick)
                      {
                          await hub.Invoke("Picking", 0);
                          return;
                      }

                      var pickedCount = Guest.Picking(noodles);
                      ServedInformation = string.Join("\r\n", ServedInformation, Guest.Eat(noodles.Take(pickedCount)));
                      await hub.Invoke("Picking", pickedCount);
                  }
                  finally
                  {
                      _flowing = false;
                      _isPick = false;
                  }
              });
        }
Esempio n. 27
0
 public MainWindow()
 {
     InitializeComponent();
     connection = new HubConnection(@"http://iskenxan-001-site1.btempurl.com/signalr");
     myHub = connection.CreateHubProxy("ChatHub");
     UserNameTextBox.Focus();
 }
Esempio n. 28
0
 public async Task SetHub(IHubProxy hub)
 {
     this.hub = hub;
     hub.On<string>("info", info => ServedInformation = string.Join("\r\n", ServedInformation, info));
     hub.On("completed", () => _isCompleted = true);
     await hub.Invoke("SetupServer");
 }
Esempio n. 29
0
 public CrestLogger()
 {
     var hubConnection = new HubConnection("http://www.contoso.com/");
     errorLogHubProxy = hubConnection.CreateHubProxy("ErrorLogHub");
     //errorLogHubProxy.On<Error>("LogError", error => { });
     hubConnection.Start().Wait();
 }
Esempio n. 30
0
    public WatchrAppender()
    {
        var appIdSetting = ConfigurationManager.AppSettings["watchr.appid"];

            // check local configuration to enusure appid is specified
            if (appIdSetting != null)
            {
                Guid appIdTemp = Guid.Empty;
                if (Guid.TryParse(appIdSetting, out appIdTemp))
                {
                    canProcess = true;
                    appId = appIdTemp;
                }
            }

            // create the connection.
            if (canProcess)
            {
                eventHub = hubConnection.Value.CreateHubProxy("EventHub");
                hubConnection.Value.Start().ContinueWith(StartConnection()).Wait();
                hubConnection.Value.Reconnecting += Value_Reconnecting;
                hubConnection.Value.Closed += Value_Closed;
                hubConnection.Value.Reconnected += Value_Reconnected;
                reconnectTimer.Elapsed += reconnectTimer_Elapsed;
            }

            if (canProcess && appId.HasValue && hubConnection.Value.State == ConnectionState.Connected)
            {
                eventHub.Invoke("RegisterApplication", appId).ContinueWith(RegisterApplication());
            }
    }
Esempio n. 31
0
        private async void ConnectAndDoThatThang()
        {
            try
            {
                // Connect to the server
                hubConnection = new HubConnection("http://192.168.10.2:5000");
                chatHubProxy  = hubConnection.CreateHubProxy("ChatroomHub");

                chatHubProxy.On <MessageViewModel>("onMessage", message =>
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                    {
                        Messages.Add(message);
                    });
                });

                await hubConnection.Start();
            }
            catch (Exception e)
            {
                await DisplayAlert("Oops", e.Message, "Ok");
            }
        }
Esempio n. 32
0
        public virtual IHubProxy BuildSignalRClient(OAuthToken token = null, Action <string, dynamic> onMessageReceived = null)
        {
            HubConnection hubConnection = new HubConnection(Uri);

            if (token != null)
            {
                hubConnection.Headers.Add("Authorization", $"{token.token_type} {token.access_token}");
            }

            IHubProxy hubProxy = hubConnection.CreateHubProxy(nameof(MessagesHub));

            if (onMessageReceived != null)
            {
                hubProxy.On("OnMessageReceived", (dataAsJson) =>
                {
                    onMessageReceived("OnMessageReceived", new SignalRMessageContentFormatter().DeSerialize <dynamic>(dataAsJson));
                });
            }

            hubConnection.Start(new LongPollingTransport(new SignalRHttpClient(GetHttpMessageHandler()))).Wait();

            return(hubProxy);
        }
Esempio n. 33
0
        public async System.Threading.Tasks.Task ConnectAsync()
        {
            Connection         = new HubConnection(ServerURI);
            Connection.Closed += Connection_Closed;
            HubProxy           = Connection.CreateHubProxy("MyHub");

            //Handle incoming event from server: use Invoke to write to console from SignalR's thread
            HubProxy.On <string, string>("AddMessage", (name, message) =>
                                         Console.WriteLine(String.Format("{0}: {1}" + Environment.NewLine, name, message))
                                         );
            try
            {
                await Connection.Start();
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Unable to connect to server: Start server before connecting clients.");
                //No connection: Don't enable Send button or show chat UI
                return;
            }

            Console.WriteLine("Connected to server at " + ServerURI + Environment.NewLine);
        }
Esempio n. 34
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    try
                    {
                        hubConnection.Stop();
                    }
                    catch { }
                    try
                    {
                        hubConnection.Dispose();
                    }
                    catch { }
                }
                eventHubProxy = null;
                hubConnection = null;

                disposedValue = true;
            }
        }
Esempio n. 35
0
 async public void makeConnection()
 {
     try
     {
         var hubConnection = new HubConnection("http://bananasvc.azurewebsites.net");
         chat    = hubConnection.CreateHubProxy("ChatHub");
         Context = SynchronizationContext.Current;
         chat.On <string, string>("broadcastMessage",
                                  (name, message) =>
                                  Context.Post(delegate
         {
             if (message.Equals("200"))
             {
                 tbstatus.Text = "Elevador Chegou!!!";
             }
         }, null)
                                  );
         await hubConnection.Start();
     }
     catch (Exception ex)
     {
     }
 }
        public RemoteQueryTraceEngine(IConnectionManager connectionManager, List <DaxStudioTraceEventClass> events, int port, IGlobalOptions globalOptions, bool filterForCurrentSession, string powerBIFileName)
        {
            Log.Debug("{{class} {method} {message}", "RemoteQueryTraceEngine", "constructor", "entered");
            // connect to hub
            hubConnection      = new HubConnection(string.Format("http://*****:*****@"d:\temp\SignalR_ClientLog.txt");
            //writer.AutoFlush = true;
            //hubConnection.TraceLevel = TraceLevels.All;
            //hubConnection.TraceWriter = writer;

            queryTraceHubProxy.On("OnTraceStarted", () => { OnTraceStarted(); });
            queryTraceHubProxy.On("OnTraceComplete", (e) => { OnTraceComplete(e); });
            queryTraceHubProxy.On <string>("OnTraceError", (msg) => { OnTraceError(msg); });
            hubConnection.Start().Wait();
            // configure trace
            Log.Debug("{class} {method} {message} connectionType: {connectionType} sessionId: {sessionId} eventCount: {eventCount}", "RemoteQueryTraceEngine", "<constructor>", "about to create remote engine", connectionManager.Type.ToString(), connectionManager.SessionId, events.Count);
            queryTraceHubProxy.Invoke("ConstructQueryTraceEngine", connectionManager.Type, connectionManager.SessionId, events, filterForCurrentSession, _powerBIFileName).Wait();
            // wire up hub events
        }
Esempio n. 37
0
        public static async void ChatConnect(string key)
        {
            connectedServerKey = key;
            ConnectionHub      = new HubConnection(url);
            ConnectionProxy    = ConnectionHub.CreateHubProxy("ChatHub");
            ConnectionProxy.On <string, string>("addChatMessage", (name, message) =>
                                                PostMessage(new MessageReceive()
            {
                Username = name,
                Message  = message
            })
                                                );
            long start = DateTime.Now.Ticks;
            await ConnectionHub.Start();

            await ConnectionProxy.Invoke("JoinChat", connectedServerKey);

            long    end     = DateTime.Now.Ticks;
            decimal elapsed = (end - start) / 10000;

            elapsed = elapsed / 1000;
            Console.WriteLine("Connected to " + url + " in " + elapsed + " seconds.");
        }
Esempio n. 38
0
        public async Task Start()
        {
            _hubConnection = new HubConnection("http://192.168.1.155/CodevelopService");
            //_hubConnection = new HubConnection(@"http://smartsolar.azurewebsites.net");
            var writer = new DebugTextWriter();

            _hubConnection.TraceLevel    = TraceLevels.All;
            _hubConnection.TraceWriter   = writer;
            _hubConnection.Error        += _hubConnection_Error;
            _hubConnection.StateChanged += _hubConnection_StateChanged;


            // set up backchannel
            _hubProxy = _hubConnection.CreateHubProxy("DeviceFeed");

            _hubProxy.On <string>("hello", message =>
                                  LogMessage(message)
                                  );


            LogMessage("Starting");
            await _hubConnection.Start();
        }
Esempio n. 39
0
        public virtual async Task <IHubProxy> BuildSignalRClient(TokenResponse token = null, Action <string, dynamic> onMessageReceived = null)
        {
            HubConnection hubConnection = new HubConnection(Uri);

            if (token != null)
            {
                hubConnection.Headers.Add("Authorization", $"{token.TokenType} {token.AccessToken}");
            }

            IHubProxy hubProxy = hubConnection.CreateHubProxy(nameof(MessagesHub));

            if (onMessageReceived != null)
            {
                hubProxy.On <string, string>("OnMessageReceived", (key, dataAsJson) =>
                {
                    onMessageReceived(key, new TestSignalRMessageContentFormatter().DeSerialize <dynamic>(dataAsJson));
                });
            }

            await hubConnection.Start(new ServerSentEventsTransport(new SignalRHttpClient(GetHttpMessageHandler())));

            return(hubProxy);
        }
Esempio n. 40
0
        public void HubNamesAreNotCaseSensitive()
        {
            using (var host = new MemoryHost())
            {
                host.MapHubs();

                var       hubConnection = new HubConnection("http://fake");
                IHubProxy proxy         = hubConnection.CreateHubProxy("chatHub");
                var       wh            = new ManualResetEvent(false);

                proxy.On("addMessage", data =>
                {
                    Assert.Equal("hello", data);
                    wh.Set();
                });

                hubConnection.Start(host).Wait();

                proxy.Invoke("Send", "hello").Wait();

                Assert.True(wh.WaitOne(TimeSpan.FromSeconds(5)));
            }
        }
Esempio n. 41
0
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation <MyNavigationPage>("Navigation");
            containerRegistry.RegisterForNavigation <FindRoomPage>("FindRoom");
            containerRegistry.RegisterForNavigation <ChatRoomPage>("ChatRoom");
            containerRegistry.RegisterForNavigation <MyTabbedPage>("Main");
            containerRegistry.RegisterForNavigation <RoomListPage>("RoomList");
            containerRegistry.RegisterForNavigation <SettingsPage>("Settings");
            containerRegistry.RegisterForNavigation <MemberListPage>("MemberList");
            containerRegistry.RegisterForNavigation <FriendListPage>("FriendList");
            containerRegistry.RegisterForNavigation <LogInPage>("LogIn");
            containerRegistry.RegisterForNavigation <CreateAccountPage>("CreateAccount");
            containerRegistry.RegisterForNavigation <InviteFriendPage>("InviteFriend");
            List <Tuple <HubConnection, IHubProxy> > list = new List <Tuple <HubConnection, IHubProxy> >();

            while (list.Count < 3)
            {
                HubConnection connection = new HubConnection(string.Format("{0}://{1}:{2}", Common_Library.ConnectionInformation.Protocol, Common_Library.ConnectionInformation.IPAddress, Common_Library.ConnectionInformation.PortNumber));
                IHubProxy     hubproxy   = connection.CreateHubProxy("ChatHub");
                list.Add(new Tuple <HubConnection, IHubProxy>(connection, hubproxy));
            }
            containerRegistry.RegisterInstance(typeof(List <Tuple <HubConnection, IHubProxy> >), list);
        }
Esempio n. 42
0
        /// <summary>
        /// 初始化服务连接
        /// </summary>
        public void InitHub(string serverUrl, string hubName)
        {
            string url = @"http://localhost:12345";

            if (string.IsNullOrEmpty(serverUrl))
            {
                serverUrl = url;
            }
            //创建连接对象,并实现相关事件
            _Connection = new HubConnection(serverUrl);

            //实现相关事件
            _Connection.Closed                 += HubConnection_Closed;
            _Connection.Received               += HubConnection_Received;
            _Connection.Reconnected            += HubConnection_Reconnected;
            _Connection.TransportConnectTimeout = new TimeSpan(DataCommon.ClientConnectTimeout);

            //绑定一个集线器
            //根据hub名创建代理,一些操作由这个代理来做
            hubProxy = _Connection.CreateHubProxy(hubName);

            //AddProtocal();
        }
Esempio n. 43
0
        private void SignalR()
        {
            //Connect to the url
            conn = new HubConnection("https://adivinaquiensoy.azurewebsites.net/");
            //conn = new HubConnection("http://localhost:50268/");
            //ChatHub is the hub name defined in the host program.

            ChatProxy = conn.CreateHubProxy("ChatHub");
            conn.Start();

            ChatProxy.On <ChatMessage>("agregarMensaje", addMessage);
            ChatProxy.On("abandoPartida", volverLobby);
            ChatProxy.On("cambiarTurno", cambiarTurno);
            ChatProxy.On <clsCarta, string>("comprobarGanador", comprobarGanador);
            ChatProxy.On <string>("finalizarPartidaPorGanador", finalizarPartidaPorGanador);
            ChatProxy.On("falloAdivinar", actualizarIntentos);
            ChatProxy.On <string>("finalizarPartidaPorFallos", finalizarPartidaPorFallos);
            ChatProxy.On("salirAbriptamente", salirPorAbandono);
            ChatProxy.On("actualizarJugadoresConectados", actualizarJugadoresConectados);
            ChatProxy.On <int>("cambiarMiTurno", cambiarMiTurno);

            //ChatProxy.On<ChatMessage>("agregarMensaje", addMessage);
        }
        public async Task ConnectAsync()
        {
            connection = new HubConnection(url);
            hubProxy   = connection.CreateHubProxy("ChatHub");
            hubProxy.On <User>("ParticipantLogin", (u) => ParticipantLoggedIn?.Invoke(u));
            hubProxy.On <string>("ParticipantLogout", (n) => ParticipantLoggedOut?.Invoke(n));
            hubProxy.On <string>("ParticipantDisconnection", (n) => ParticipantDisconnected?.Invoke(n));
            hubProxy.On <string>("ParticipantReconnection", (n) => ParticipantReconnected?.Invoke(n));
            hubProxy.On <string, string>("BroadcastTextMessage", (n, m) => NewTextMessage?.Invoke(n, m, MessageType.Broadcast));
            hubProxy.On <string, byte[]>("BroadcastPictureMessage", (n, m) => NewImageMessage?.Invoke(n, m, MessageType.Broadcast));
            hubProxy.On <string, string>("UnicastTextMessage", (n, m) => NewTextMessage?.Invoke(n, m, MessageType.Unicast));
            hubProxy.On <string, byte[]>("UnicastPictureMessage", (n, m) => NewImageMessage?.Invoke(n, m, MessageType.Unicast));
            hubProxy.On <User>("UnicastFriendshipRequest", (u) => NewFriendshipRequest?.Invoke(u, MessageType.Unicast));
            hubProxy.On <User>("AddFriend", (u) => NewFriendshipAdd?.Invoke(u, MessageType.Unicast));
            hubProxy.On <string>("ParticipantTyping", (p) => ParticipantTyping?.Invoke(p));

            connection.Reconnecting += Reconnecting;
            connection.Reconnected  += Reconnected;
            connection.Closed       += Disconnected;

            ServicePointManager.DefaultConnectionLimit = 10;
            await connection.Start();
        }
Esempio n. 45
0
        public void HubNamesAreNotCaseSensitive(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(5)));
            }
        }
Esempio n. 46
0
        public async Task <bool> ConnectAsync(bool isUnitTesting = false)
        {
            Connection = new HubConnection(Constants.protocol + ServerIP + ":" + Constants.serverPort + Constants.serverEndPoint);
            hubProxy   = Connection.CreateHubProxy("MainHub");
            hubProxy.On <string>("announceClientLoggedIn", (u) => announceClientLoggedIn?.Invoke(u));
            hubProxy.On <string>("clientLogout", (n) => clientLoggedOut?.Invoke(n));
            hubProxy.On <string>("ClientDisconnected", (n) => ClientDisconnected?.Invoke(n));
            hubProxy.On <string>("ClientReconnected", (n) => ClientReconnected?.Invoke(n));
            //hubProxy.On<string>("OnConnected", (n) => OnConnected?.Invoke(n));

            Connection.Reconnecting += Reconnecting;
            Connection.Reconnected  += Reconnected;
            Connection.Closed       += Disconnected;

            ServicePointManager.DefaultConnectionLimit = 100;
            await Connection.Start();

            bool connectionStatus = Connection.State == ConnectionState.Connected ? true : false;

            NetworkController.IsConnected = connectionStatus;

            return(connectionStatus);
        }
Esempio n. 47
0
        private async void InitSignalR()
        {
            slider.IsEnabled = false;
            textbl.Text      = "Connecting to SignalR Server";

            await Task.Run(async() =>
            {
                SignalRClient signalR = new SignalRClient();
                signalR.InitializeSignalR();
                signalR.ValueChanged += ValueChanged;
                hub = signalR.SignalRHub;

                await Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal, () =>
                {
                    slider.ValueChanged += (s, e) => textbl.Text = e.NewValue.ToString();
                    slider.PointerMoved += (s, e) => SendMessage("SLIDER", slider.Value);

                    textbl.Text      = "Connected...!";
                    slider.IsEnabled = true;
                });
            });
        }
Esempio n. 48
0
        public BackplaneServiceClient(IUrlProvider urlProvider, IHttpServiceClient httpServiceClient)
        {
            _urlProvider       = urlProvider;
            _httpServiceClient = httpServiceClient;

            _hubConnection = new HubConnection(_urlProvider.BackplaneUrl, true);

            _hubProxy = _hubConnection.CreateHubProxy("BroadcastHub");

            ConnectionStateStream = Observable.Create <ConnectionState>(observer =>
            {
                observer.OnNext(ConnectionState.Disconnected);

                return(Observable.FromEvent <StateChange>(
                           h => _hubConnection.StateChanged += h,
                           h => _hubConnection.StateChanged -= h)
                       .Subscribe(s => observer.OnNext(s.NewState)));
            });

            TokenAvailabilityStream = Observable.Create <bool>(observer =>
                                                               _hubProxy.On <bool>("OnTokenAvailability", observer.OnNext))
                                      .DistinctUntilChanged();
        }
Esempio n. 49
0
        private void BeginNewConnection()
        {
            try
            {
                Connection = new HubConnection(_target.Uri);
                var credentials = GetBasicAuthenticationCredentials();
                if (credentials != null)
                {
                    var credentialString       = credentials.UserName + ":" + credentials.Password;
                    var credentialBytes        = System.Text.Encoding.ASCII.GetBytes(credentialString);
                    var credentialBase64String = Convert.ToBase64String(credentialBytes);
                    Connection.Headers.Add("Authorization", "Basic " + credentialBase64String);
                }
                _proxy = Connection.CreateHubProxy(_target.HubName);
                Connection.Start().Wait();

                _proxy.Invoke("Notify", Connection.ConnectionId);
            }
            catch (Exception)
            {
                _proxy = null;
            }
        }
        public async void On3()
        {
            using (HubConnection connection = new HubConnection(BaseUrl))
            {
                IHubProxy hubProxy = connection.CreateHubProxy("TestHub");
                await connection.Start();

                ManualResetEvent resetEvent = new ManualResetEvent(false);

                int value1 = 0;
                int value2 = 0;
                int value3 = 0;

                hubProxy.On <int, int, int>("ClientCallback", (v1, v2, v3) => { value1 = v1; value2 = v2; value3 = v3; resetEvent.Set(); });

                await hubProxy.Invoke("InvokeClientCallback3", 1, 2, 3);

                Assert.True(resetEvent.WaitOne(3000));
                Assert.Equal(1, value1);
                Assert.Equal(2, value2);
                Assert.Equal(3, value3);
            }
        }
Esempio n. 51
0
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:56472/";

            Console.ReadLine();
            var       hubConnection = new HubConnection(baseAddress);
            IHubProxy eventHubProxy = hubConnection.CreateHubProxy("ChatHub");

            eventHubProxy.On <string, MessageEvent>("OnEvent", (channel, ev) =>
            {
                Console.WriteLine($"Event received on {channel} channel - {ev.Message}");
            });
            hubConnection.Start().Wait();

            // Join the channel for task updates in our console window
            //
            eventHubProxy.Invoke("Subscribe", "e7de7c74-14a4-4541-bd95-512a2717e7ab");
            eventHubProxy.Invoke("Subscribe", "demoRoom");

            Console.WriteLine($"Server is running on {baseAddress}");
            Console.WriteLine("Press <enter> to stop server");
            Console.ReadLine();
        }
Esempio n. 52
0
 protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     _hub                   = new HubConnection("http://localhost:9638/");
     _drawingBoard          = _hub.CreateHubProxy("DrawingBoard");
     _drawingBoard["color"] = 1; // Black;
     _drawingBoard.On <int, int, int>("DrawPoint", (x, y, c) => Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         DrawPoint(x, y, c);
     }
                                                                                    ));
     _drawingBoard.On("Clear", () => Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         ClearDrawingBoard();
     }
                                                         ));
     _drawingBoard.On <int[, ]>("Update", (int[,] buffer) => Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         UpdateDrawingBoard(buffer);
     }
                                                                                 ));
     await _hub.Start();
 }
        private void PrecificarCotacoesFornecedor()
        {
            try
            {
                Connection = new HubConnection(Url);
                Proxy      = Connection.CreateHubProxy("Notificacoes");
                Connection.Start();

                PrecoCotacaoFornecedorService service = new PrecoCotacaoFornecedorService();
                eventLog2.WriteEntry($"Precificando Cotação Fornecedor.", EventLogEntryType.Information, 1);
                var resultado = service.PrecificarCotacaoFornecedor();

                resultado.ForEach(x => {
                    Proxy.Invoke("CotacaoNovoPreco", x.TokenUsuario, x.CotacaoId, x.DataFechamentoCotacao, x.CotacaoGrupo, DateTime.Now);
                });

                eventLog2.WriteEntry($"Precificação de Cotações para Fornecedores executada com sucesso!", EventLogEntryType.Information, 1);
            }
            catch (Exception ex)
            {
                eventLog2.WriteEntry($"Erro ao Precificar Cotações para Fornecedores.\n\n{ex}", EventLogEntryType.Error, 1);
            }
        }
        public ChatRoom(IHubProxy hub, string userName, string roomName)
        {
            this.room = roomName;
            this.user = userName;
            this.hub  = hub;

            // broadcast
            this.hub.On <string, string>(nameof(EnumAcciones.broadcast),
                                         (n, m) => MessageRecived?.Invoke(n, m)
                                         );

            //SendRoom
            this.hub.On <string, string>(nameof(EnumAcciones.sendRoom),
                                         (n, m) => MessageRecived?.Invoke(n, m)
                                         );

            //SendPrivate
            this.hub.On <string, string>(nameof(EnumAcciones.sendPrivate),
                                         (n, m) => PrivateMessageRecived?.Invoke(n, m)
                                         );

            hub.Invoke(nameof(EnumAcciones.joinRoom), room);
        }
Esempio n. 55
0
        private static async Task ReceiveMessagesFromDeviceAsync(string partition, IHubProxy hubProxy, CancellationToken ct)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                await hubProxy.Invoke("Send", new object[] { (object)"Partition: " + partition, (object)data });

                Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
            }
        }
Esempio n. 56
0
        private async Task Init()
        {
            if (_approaching == null)
            {
                _approaching = new Dictionary <int, TimeSpan>();
            }

            if (_departed == null)
            {
                _departed = new Dictionary <int, TimeSpan>();
            }

            if (_hub == null)
            {
                var signalrUri = CloudConfigurationManager.GetSetting("signalrUri");

                var conn = new HubConnection(signalrUri);

                _hub = conn.CreateHubProxy("MapHub");

                await conn.Start();
            }
        }
Esempio n. 57
0
 public ClientHubProxy(string url, string hubType)
 {
     hubConnection = new HubConnection(url);
     chatHubProxy  = hubConnection.CreateHubProxy(hubType);
     chatHubProxy.On("receivedMessage", (Parcel message) =>
     {
         OnMessageReceived(message);
     });
     chatHubProxy.On("receivedUsername", (string username) =>
     {
         OnUsernameReceived(username);
     });
     chatHubProxy.On("receivedUsernames", (ObservableCollection <string> usernames) =>
     {
         OnUsernamesReceived(usernames);
     });
     chatHubProxy.On("receivedUsernameDisconnect", (string username) =>
     {
         OnUsernameReceivedDisconnect(username);
     });
     chatHubProxy.On("getLog", (ObservableCollection <string> log) =>
     {
         OnLogReceived(log);
     });
     chatHubProxy.On("receivedLocalusername", (string username) =>
     {
         OnReceivedLocalUsername(username);
     });
     chatHubProxy.On("getLogin", (bool loggedIn) =>
     {
         OnLoggedIn(loggedIn);
     });
     chatHubProxy.On("getSignup", (bool signedUp) =>
     {
         OnSignedUp(signedUp);
     });
 }
Esempio n. 58
0
        public static void Start()
        {
            var hubConnection = new HubConnection("https://arktin.azurewebsites.net/");
            //var cookieToken = "HdR3ISBq8HLaczEbn_gXcJfn_MhlNoXZ6ydUoJiJbfx1-i5vtGvBHFlXT0kiACLPFQRj8O_O1XSeQwh-4OmypHKg9FUYrt3frhYXu1k956IODyRNW4hfa7K-e33YcTJtg0begPvEWeS92I0OcdbU-5-8RU0wTira_tUsJhis-o1It7gOv6lJHx_7ssjq7pzM2OaKOlA-3ir9oN40C6V5WrQEsjxEeiuSBaVaGakejvDCwOnivUUr0NQ40ABuDP-KXeElnRfYUxx_xu3OUgO3uj7vmqc2moRnrI7oDQo7mCHlWNwI4icQ4rroNdXBJaJVyayaSTZj7TktnAFCIJmeRGdBv96p0CQlqQf7iquT4KqfT2GrgnUnUhL5othFhe7CUBIKmbWwIGu-rFU-7lE70y6HciaSqxBnJqdvu_jpj8H85_QfkIYUNNzIXoTOSadkXBhKLOtOBauaJ8F5yCvaZwea4uj14hW_feDw-BKSQ7kjMsQDjhWkUCkY6_PR7vpM";
            const string bearerToken = "7KWzUFpTmXjYPHJf45R9XKkoEGrtanwgiCLzfBoPDOaFivZ0HFpuF0I5j1X0KYfYywCBPbxVjDOdN6UD3UP5fPE4mguU41E3C6HvGHgFS4XQMOOfpcfOSwQEklBLBnIYbs-XcDt2U2o-KaiDYpsAuCVq6va8lqd_QBLiCYrWkbllYScFNnG05zPgsZ6N27mYyEUNhAxnaLXBou7QR9EsxEqHjJLLKYPxcWNHMmjRF8BiufEW8f711Zaf8eX3m7_WKyR6RRF65vI7spEX8JW2-RDs9iI-rjC8Q696mWlp5XJp3R0o3WyVHA47rm0X83dezBtAZj6AkahnYlJVWhWVn_nmSKX-ROdZ32UBVNhYsP5kNJICCIMdVt5ycU2qb_NC3dGt1_yRu0aktHOISw_ZAsvRIhCz6BmP9842VBauDDXdkIdnLb5OZgvFZR0lLeZFE6EdnqI4Q8aNuqfE1VeG_fx44ybODYkXAQbMdeVCYX0"; //"9AmuGmqFhoyXXU3lDNuxrIyml70WvmFSZkLCmQCE47R7h2AU0Z7R91KtXgqr3sJ5U61wkcJF_WFdnJE4VHbTiQxPYcCplQzfTBMZG-jtj_4MGgnndDBIlSC9wEXJLQWhxQeCAoT5EQ9KF4_i9AKbsUMiFscmDEl7PBitaBJeIfSV0GLMnY2_AfTBYbP72iP9n39QJkJEM6mmfCur4Oy1Elv9g3XAPsMXnANkWP6o_d-AwhP5aGtrODp5PbJCwF6iJE5mALbrj6BaK5VAc3YgsLwqXpM_bNCYHJrNBssq8l4QhtbWLBS_UDSgne0swg041wvtLIGjnqJsrtFn-IND4iXmRJ6prXRB1kmg8gI_XJm1ZxxgT9lYT-IJj7SPMMQZAuQebjxFMwduTcSAP8ISIa4CUyoT47uBPAl7nOg_Ee7K2kyOunDUBIvjPK2HsJZsu1YuDgEMURlBob32SNXj0025BhgG6xLWZjddWtTebx5ft61l6ReR4gBO6nBUpYSs";

            //var cookie = new Cookie("ArktinMonitorCookie", token2){Domain = "arktin.azurewebsites.net" };
            //hubConnection.CookieContainer = new CookieContainer();
            //hubConnection.CookieContainer.Add(cookie);
            hubConnection.Headers.Add("Authorization", "Bearer " + bearerToken);
            //hubConnection.TraceLevel = TraceLevels.All;
            //hubConnection.TraceWriter = Console.Out;
            IHubProxy myHubProxy = hubConnection.CreateHubProxy("TempHub");

            myHubProxy.On <string, string>("addNewMessageToPage",
                                           (name, message) => Console.Write($"{name} - {message}\n"));

            hubConnection.Start().Wait();
            //System.Threading.Thread.Sleep(5000);

            while (true)
            {
                //System.Threading.Thread.Sleep(1000);

                myHubProxy.Invoke("SendKeys", "service", Console.ReadLine()).ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        if (task.Exception != null)
                        {
                            Console.WriteLine("There was an error opening the connection:{0}",
                                              task.Exception.GetBaseException());
                        }
                    }
                }).Wait();
            }
        }
Esempio n. 59
0
        public bool InitRoom(string uri)
        {
            bool bInit = false;

            try
            {
                if (liveBack == null)
                {
                    return(false);
                }
                Connection = new HubConnection(uri);
                HubProxy   = Connection.CreateHubProxy("OeipLive");
                onActions.Add(HubProxy.On("OnLoginRoom", (int code, string server, int port) =>
                {
                    liveBack?.OnLoginRoom(code, server, port);
                }));
                onActions.Add(HubProxy.On("OnUserChange", (int userId, bool bAdd) =>
                {
                    liveBack?.OnUserChange(userId, bAdd);
                }));
                onActions.Add(HubProxy.On("OnStreamUpdate", (int userId, int index, bool bAdd) =>
                {
                    liveBack?.OnStreamUpdate(userId, index, bAdd);
                }));
                onActions.Add(HubProxy.On("OnLogoutRoom", () =>
                {
                    liveBack?.OnLogoutRoom();
                }));
                Connection.Start().Wait();
                bInit = true;
            }
            catch (Exception)
            {
                bInit = false;
            }
            return(bInit);
        }
Esempio n. 60
0
        static void Main(string[] args)
        {
            HubConnection connection = null;
            IHubProxy     myHub      = null;
            string        url        = "http://localhost:8889";


            IDictionary <string, string> dl = new Dictionary <string, string>();

            dl.Add("UserID", "hant");
            dl.Add("UserName", "韩涛");
            dl.Add("DepartmentID", "001");
            dl.Add("DeviceType", "1");//1代表PC客户端
            connection = new HubConnection(url, dl);
            //类名必须与服务端一致
            myHub = connection.CreateHubProxy("SignalRHub");

            //方法名必须与服务端一致
            myHub.On <object>("receive", (message) =>
            {
                JObject jobject = message as JObject;
                Console.WriteLine("发送人:" + jobject["username"]);
                Console.WriteLine("消  息:" + jobject["content"]);
            });
            connection.Start().ContinueWith(task =>
            {
                if (!task.IsFaulted)
                {
                    Console.WriteLine("连接成功");
                }
                else
                {
                    Console.WriteLine("连接失败");
                }
            }).Wait();
            Console.ReadLine();
        }