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; }); }); }
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))); } } }
public async Task <bool> ConnectForSignalAsync(string hubName, TextWriter traceOutput = null) { HubConnection = new Microsoft.AspNet.SignalR.Client.HubConnection("http://serverdown.bogus.address.com", new Dictionary <string, string> { { "bearerToken", "Random" } }); if (traceOutput != null) { HubConnection.TraceLevel = TraceLevels.All; HubConnection.TraceWriter = traceOutput; } HubProxy = HubConnection.CreateHubProxy(hubName); HubProxy.On <object>("OnEventMessage", OnEventMessage); try { await HubConnection.Start(); return(true); } catch (HttpRequestException e) { return(false); } }
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; } }
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); } } }
//[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(); }
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"); }
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; }
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); } }
internal CustomerUpdateNotifier() { var hubConnection = new HubConnection(AppSettings.CustomerUpdateHubUrl); _hubProxy = hubConnection.CreateHubProxy(AppSettings.CustomerUpdateHubName); hubConnection.Start().Wait(); }
static void Main() { Console.WriteLine("Creating hub"); using (var hubConnection = new HubConnection("http://localhost:1906/")) { var eventHubProxy = hubConnection.CreateHubProxy("EventHub"); eventHubProxy.On<Message>("Receive", message => OnReceive(message)); //eventHubProxy.On<Message>("UpdateConfiguration", message => OnUpdateConfiguration(message)); hubConnection.Start().Wait(); //eventHubProxy.Invoke<Message>("RequestConfiguration").Wait(); Console.WriteLine("Hub created"); while (true) { Console.Write("Values: "); var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(Console.ReadLine()); var message = new Message { Sender = typeof(Program).FullName, Target = "ArtNet", Time = DateTime.Now, Values = values }; Console.WriteLine("Sending message"); eventHubProxy.Invoke<Message>("Send", message).Wait(); Console.WriteLine("Message sent"); } } }
private async void ConnectAsync() { con = new HubConnection(ServerURI); con.Closed += Connection_Closed; con.Error += Connection_Error; HubProxy = con.CreateHubProxy("MyHub"); //Handle incoming event from server: use Invoke to write to console from SignalR's thread HubProxy.On<string>("getPos", (message) => Dispatcher.BeginInvoke(() => test(message)) ); try { await con.Start(); } catch (HttpRequestException) { //No connection: Don't enable Send button or show chat UI btntrack.Content = "eror"; } catch (HttpClientException) { btntrack.Content = "eror"; } Dispatcher.BeginInvoke(() => { HubProxy.Invoke("Connect", "15"); }); }
static void Main(string[] args) { Console.Write("Enter your Name: "); name = Console.ReadLine(); HubConnection connection = new HubConnection("http://localhost:51734"); proxy = connection.CreateHubProxy("ChatHub"); connection.Received += Connection_Received; Action<string, string> SendMessageRecieved = recieved_a_message; proxy.On("broadcastMessage", SendMessageRecieved); Console.WriteLine("Waiting for connection"); connection.Start().Wait(); Console.WriteLine("You can send messages now."); connection.StateChanged += Connection_StateChanged; string input; while ((input = Console.ReadLine()) != null) { proxy.Invoke("Send", new object[] { name, input }); } }
public void Connect() { hubConnection = new HubConnection("http://localhost:9346"); hub = hubConnection.CreateHubProxy("OfficeHub"); hub.On<byte[]>("OnRequest", OnRequest); hubConnection.Start().Wait(); }
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) { } }
//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(); }
private async Task btnCon_Click(object sender, EventArgs e) { this.btnInvok.Enabled = false; hubConnection = new HubConnection(txtUrl.Text); stockTickerHubProxy = hubConnection.CreateHubProxy("TickerHub"); strongHubProxy = hubConnection.CreateHubProxy("StrongHub"); this.btnCon.Enabled = false; try { await hubConnection.Start(new WebSocketTransport()); this.btnInvok.Enabled = true; } catch (Exception ex) { Exception temp = ex; string msg = temp.Message; while (temp.InnerException != null) { temp = temp.InnerException; msg += "\r\n" + temp.Message; } MessageBox.Show(msg); } this.btnCon.Enabled = true; }
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); }
public SignalRProxySingleton() { conn = new HubConnection(ConfigurationManager.AppSettings["SignalRURL"]); homeHub = conn.CreateHubProxy(ConfigurationManager.AppSettings["HubName"]); conn.Start().GetAwaiter().GetResult(); }
public void Run() { System.Console.WriteLine("Starting connection to host at: {0} with launcher identifier name as {1}", AppSettings.HostUrl, AppSettings.LauncherName); var hubConnection = new HubConnection(AppSettings.HostUrl); IHubProxy hubProxy = hubConnection.CreateHubProxy("LauncherHub"); hubProxy.On<LauncherCommand>("sendCommand", OnSendCommand); hubProxy.On<IEnumerable<LauncherSequence>>("sendSequence", OnSendSequence); ServicePointManager.DefaultConnectionLimit = 10; hubConnection.Start().Wait(); hubConnection.StateChanged += change => { System.Console.WriteLine("Connection to host state has changed to : " + change.NewState); if (change.NewState == ConnectionState.Connected) { hubProxy.Invoke("Initialize", AppSettings.LauncherName); } }; hubProxy.Invoke("Initialize", AppSettings.LauncherName); System.Console.WriteLine("Connection established.... waiting for commands from host..."); while (true) { // let the app know we are health every 1000 (Ms = 1 second) * 60 sec = 1 min * Thread.Sleep(1000 * 60 * 5); hubProxy.Invoke("Initialize", AppSettings.LauncherName); } }
public async static Task<IHubProxy> GetProxy(String hubName) { var hubConnection = new HubConnection(ConfigurationManager.AppSettings.Get("ServerAddressAndPort")); IHubProxy proxy = null; switch (hubName) { case "UserHub": { proxy = hubConnection.CreateHubProxy("UserHub"); break; } case "MessageHub": { proxy = hubConnection.CreateHubProxy("MessageHub"); break; } case "ConversationHub": { proxy = hubConnection.CreateHubProxy("ConversationHub"); break; } } ServicePointManager.DefaultConnectionLimit = 20; await hubConnection.Start(); return proxy; }
public CrestLogger() { var hubConnection = new HubConnection("http://www.contoso.com/"); errorLogHubProxy = hubConnection.CreateHubProxy("ErrorLogHub"); //errorLogHubProxy.On<Error>("LogError", error => { }); hubConnection.Start().Wait(); }
/// <summary> /// Setups the notifications. /// </summary> public async void SetupNotifications(Action action) { var hubConnection = new HubConnection(Application.Current.Host.Source.GetComponents(UriComponents.Scheme | UriComponents.HostAndPort, UriFormat.Unescaped)); var proxy = hubConnection.CreateHubProxy(CommunicationConstants.RuntimeHubName); proxy.On<int>( CommunicationConstants.ActionsChangedEventName, personId => { if (personId == Utils.CurrentUserPersonId || personId == CommunicationConstants.BroadcastPersonId) { Deployment.Current.Dispatcher.BeginInvoke(action); } }); hubConnection.TraceWriter = Console.Out; try { await hubConnection.Start(); } catch (Exception ex) { Logger.Log(LogSeverity.Error, "SignalR Hub Connection Error", ex); } }
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; } }
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(); }
static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.ColoredConsole() .CreateLogger(); string baseAddress = "http://*****:*****@ev}", channel, ev)); hubConnection.Start().Wait(); // Join the channel for task updates in our console window // eventHubProxy.Invoke("Subscribe", Constants.AdminChannel); eventHubProxy.Invoke("Subscribe", Constants.TaskChannel); Console.WriteLine($"Server is running on {baseAddress}"); Console.WriteLine("Press <enter> to stop server"); Console.ReadLine(); } }
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; } }
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!"); }
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(); }
public void OpenConnection() { _connection = new HubConnection(_hubUrl); _alertHubProxy = _connection.CreateHubProxy("alertHub"); _resourceHubProxy = _connection.CreateHubProxy("resourceHub"); _connection.Start().Wait(); }
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}"); } }
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); } }
private void Connect() { _hub = _connection.CreateHubProxy("CommHub"); _connection.Start().Wait(); NotifyLogMessageEvent("Hub started"); _hub.Invoke("Connect", _machineData); NotifyLogMessageEvent("Connected to hub"); }
public async Task ConnectStatusStreamAsync() { if (_connectionConfig.ServerMode == "v1") { // older signalr client/server _legacyConnection = new Microsoft.AspNet.SignalR.Client.HubConnection(_statusHubUri); _legacyConnection.Credentials = System.Net.CredentialCache.DefaultCredentials; var hubProxy = _legacyConnection.CreateHubProxy("StatusHub"); hubProxy.On<ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) => OnManagedCertificateUpdated?.Invoke(u)); hubProxy.On<RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) => OnRequestProgressStateUpdated?.Invoke(s)); hubProxy.On<string, string>(Providers.StatusHubMessages.SendMsg, (a, b) => OnMessageFromService?.Invoke(a, b)); _legacyConnection.Reconnecting += OnConnectionReconnecting; _legacyConnection.Reconnected += OnConnectionReconnected; _legacyConnection.Closed += OnConnectionClosed; await _legacyConnection.Start(); } else { // newer signalr client/server // TODO: auth: https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1 connection = new HubConnectionBuilder() .WithUrl(_statusHubUri) .WithAutomaticReconnect() .AddMessagePackProtocol() .Build(); connection.Closed += async (error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; connection.On<RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) => { OnRequestProgressStateUpdated?.Invoke(s); }); connection.On<ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) => { OnManagedCertificateUpdated?.Invoke(u); }); connection.On<string, string>(Providers.StatusHubMessages.SendMsg, (a, b) => { OnMessageFromService?.Invoke(a, b); }); await connection.StartAsync(); } }
private bool AuthenticateUser(string user, string password) { _Authenticated = false; if (_UsingWindowsAuth) { try { using (var connection = new Microsoft.AspNet.SignalR.Client.HubConnection(RemoteDesktop_CSLibrary.Config.SignalRHubUrl)) { connection.TransportConnectTimeout = new TimeSpan(0, 0, 4); RemoteDesktop_CSLibrary.Config.SignalRHubUrl.Split('/').LastOrDefault(); IHubProxy stockTickerHubProxy = connection.CreateHubProxy(RemoteDesktop_CSLibrary.Config.SignalRHubName); connection.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; connection.Error += connection_Error; connection.Start().Wait(RemoteDesktop_CSLibrary.Config.AuthenticationTimeout); _Authenticated = true; return(_Authenticated); } } catch (Exception e) { _Authenticated = false; } } else { var request = WebRequest.Create(RemoteDesktop_CSLibrary.Config.AuthenticationUrl) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = new CookieContainer(); request.Timeout = RemoteDesktop_CSLibrary.Config.AuthenticationTimeout; var authCredentials = "UserName="******"&Password="******".ASPXAUTH"]; } } catch (Exception e) { Debug.WriteLine(e.Message); } _Authenticated = _AuthCookie != null; } return(_Authenticated); }
private void button1_Click(object sender, EventArgs e) { connection = new Microsoft.AspNet.SignalR.Client.HubConnection(ServerUri); //类名必须与服务端一致 //myHub = connection.CreateHubProxy("BroadcastHub"); rhub = connection.CreateHubProxy("myhub"); connection.Start();//连接服务器 label1.Text = "连接服务器成功!"; //注册客户端方法名称"addMessage"与服务器端Send方法对应,对应的 callback方法 ReceiveMsg rhub.On <string, string>("addMessage", ReceiveMsg); }
async void IniSignalR(string serverUri) { connection = new Microsoft.AspNet.SignalR.Client.HubConnection(serverUri); //类名必须与服务端一致 //myHub = connection.CreateHubProxy("BroadcastHub"); rhub = connection.CreateHubProxy("MyHub"); ////注册客户端方法名称"addMessage"与服务器端Send方法对应,对应的 callback方法 ReceiveMsg rhub.On("Register", Register); await connection.Start();//连接服务器 }
protected virtual void OnStateChanged(StateChange stateChange) { using (Trace.Log()) { connectionState = stateChange.NewState; Console.WriteLine($"{stateChange.OldState} {stateChange.NewState}"); if (stateChange.NewState == ConnectionState.Disconnected) { if (stateChange.OldState == ConnectionState.Disconnected) { hubConnection?.Start(); } else if (reconnect) { Task.Delay(1000).ContinueWith((t) => hubConnection?.Start()); } } StateChanged?.Invoke(stateChange); } }
private void Form1_Load(object sender, EventArgs e) { Connection = new Microsoft.AspNet.SignalR.Client.HubConnection(ServerUrl); Connection.Closed += Connection_Closed; HubProxy = Connection.CreateHubProxy("MyHub"); HubProxy.On <string, string>("addMessage", RecvMsg);//接收实时信息 Connection.Start().ContinueWith(task => { if (!task.IsFaulted) { msgContent.AppendText(string.Format("与Signal服务器连接成功,服务器地址:{0}\r\n", ServerUrl)); } else { msgContent.AppendText("与服务器连接失败,请确认服务器是否开启。\r\n"); } }).Wait(); }
private static void Main(string[] args) { var conn = new Microsoft.AspNet.SignalR.Client.HubConnection("http://localhost:55740/"); var hub = conn.CreateHubProxy("planHub"); hub.On <int, int>("Updated", (plan, result) => { Console.WriteLine("PLAN :{0}", plan); Console.WriteLine("RESULT:{0}", result); Console.WriteLine("DIFF :{0}", result - plan); }); conn.Start().ContinueWith(t => { if (args.Length == 2) { hub.Invoke("Update", int.Parse(args[0]), int.Parse(args[1])); } else { hub.Invoke("GetPlan"); } }); Console.ReadLine(); }
public async Task ConnectStatusStreamAsync() { if (_connectionConfig.ServerMode == "v1") { // older signalr client/server _legacyConnection = new Microsoft.AspNet.SignalR.Client.HubConnection(_statusHubUri); _legacyConnection.Credentials = System.Net.CredentialCache.DefaultCredentials; var hubProxy = _legacyConnection.CreateHubProxy("StatusHub"); hubProxy.On <ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) => OnManagedCertificateUpdated?.Invoke(u)); hubProxy.On <RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) => OnRequestProgressStateUpdated?.Invoke(s)); hubProxy.On <string, string>(Providers.StatusHubMessages.SendMsg, (a, b) => OnMessageFromService?.Invoke(a, b)); _legacyConnection.Reconnecting += OnConnectionReconnecting; _legacyConnection.Reconnected += OnConnectionReconnected; _legacyConnection.Closed += OnConnectionClosed; await _legacyConnection.Start(); } else { // newer signalr client/server // TODO: auth: https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1 connection = new HubConnectionBuilder() .WithUrl(_statusHubUri, opts => { opts.HttpMessageHandlerFactory = (message) => { if (message is System.Net.Http.HttpClientHandler clientHandler) { if (_connectionConfig.AllowUntrusted) { // allow invalid tls cert clientHandler.ServerCertificateCustomValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return(true); }; } } return(message); }; }) .WithAutomaticReconnect() .AddMessagePackProtocol() .Build(); connection.Closed += async(error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; connection.On <RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) => { OnRequestProgressStateUpdated?.Invoke(s); }); connection.On <ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) => { OnManagedCertificateUpdated?.Invoke(u); }); connection.On <string, string>(Providers.StatusHubMessages.SendMsg, (a, b) => { OnMessageFromService?.Invoke(a, b); }); await connection.StartAsync(); } }