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"); }
/* 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)); }
private static void Connect() { _hubConnection = new HubConnection(ConnectionUrl); _proxy = _hubConnection.CreateHubProxy("chat"); _hubConnection.Start().Wait(); _connected = true; }
async void Hookup() { var deviceName = ConfigurationManager.AppSettings["DeviceName"]; CurrentDevice = PTZDevice.GetDevice(deviceName, PTZType.Relative); var url = ConfigurationManager.AppSettings["relayServerUrl"]; var remoteGroup = Environment.MachineName; //They have to hardcode the group, but for us it's our machine name var connection = new HubConnection(url); var proxy = connection.CreateHubProxy("RelayHub"); proxy.On<int, int>("Move", (x, y) => { Console.WriteLine("Move({0},{1})", x, y); BoxContext.Log.DebugFormat("Move({0},{1})", x, y); CurrentDevice.Move(x, y); }); proxy.On<int>("Zoom", (z) => { Console.WriteLine("Zoom ({0})", z); BoxContext.Log.DebugFormat("Zoom ({0})", z); CurrentDevice.Zoom(z); }); try { await connection.Start(); BoxContext.Log.DebugFormat("After connection.Start()"); await proxy.Invoke("JoinRelay", remoteGroup); BoxContext.Log.DebugFormat("After JoinRelay"); BoxContext.Log.DebugFormat("Joined remote group - " + remoteGroup); } catch (Exception pants) { BoxContext.Log.ErrorFormat(pants.GetError().ToString()); throw; } }
private async void ActionWindowLoaded(object sender, RoutedEventArgs e) { if (count == 0) { id = Properties.Settings.Default.UserID; //ClientNameTextBox.Text = id; Active = true; Thread = new System.Threading.Thread(() => { Connection = new HubConnection(Host); Proxy = Connection.CreateHubProxy("SignalRMainHub"); Proxy.On<string, string>("addmessage", (name, message) => OnSendData(DateTime.Now.ToShortTimeString()+" ["+ name + "]\t " + message)); Proxy.On("heartbeat", () => OnSendData("Recieved heartbeat <3")); Proxy.On<HelloModel>("sendHelloObject", hello => OnSendData("Recieved sendHelloObject " + hello.Molly + " " + hello.Age)); Connection.Start(); while (Active) { System.Threading.Thread.Sleep(10); } }) { IsBackground = true }; Thread.Start(); count++; } }
static void Main(string[] args) { var hub = new HubConnection("http://localhost:20133"); IHubProxy client = hub.CreateHubProxy("SelfHub"); client.On<UserMessage>("addmessage", (msg) => Console.WriteLine("{0} : {1}", msg.Source,msg.Message)); hub.Start().Wait(); Console.WriteLine("Enter your name, then [enter]"); var user = Console.ReadLine() ?? "guest"; client["user"] = user; string line = null; while ((line = Console.ReadLine()) != null) { client.Invoke("Send", new UserMessage(user,line)).ContinueWith( task => { if(task.IsFaulted) Console.WriteLine("ERR : {0}",task.Exception.GetBaseException()); else Console.WriteLine("OK...Sent"); }); } }
public IHubProxy Create(string hubUrl, Action<IHubConnection> configureConnection, Action<IHubProxy> onStarted, Action reconnected, Action<Exception> faulted, Action connected) { var connection = new HubConnection(hubUrl); if (configureConnection != null) configureConnection(connection); var proxy = connection.CreateHubProxy("EventAggregatorProxyHub"); connection.Reconnected += reconnected; connection.Error += faulted; Task.Factory.StartNew(() => { try { connection.Start().Wait(); onStarted(proxy); connected(); } catch (Exception ex) { faulted(ex); } }); return proxy; }
public MainWindow() { InitializeComponent(); connection = new HubConnection("http://localhost:9081/"); var messageOverviewHub = connection.CreateHubProxy("MessageOverviewHub"); connection.StateChanged += change => { Console.WriteLine(change.OldState + " => " + change.NewState); var connectionState = change.NewState; switch (connectionState) { case ConnectionState.Connecting: break; case ConnectionState.Connected: break; case ConnectionState.Reconnecting: break; case ConnectionState.Disconnected: Connect(); break; default: throw new ArgumentOutOfRangeException(); } }; messageOverviewHub.On<MessageUpdated>("invoke", i => label1.Content = string.Format("Message was updated at {0} ", i.Time)); this.Loaded +=OnLoaded; }
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, }; }
private void 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)); hubConnection.Start().Wait(); hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name); hubProxy.Invoke("DisplayMessageCaller", "Hello Caller!").Wait(); string joinGroupResponse = hubProxy.Invoke<string>("JoinGroup", hubConnection.ConnectionId, "CommonClientGroup").Result; hubConnection.TraceWriter.WriteLine("joinGroupResponse={0}", joinGroupResponse); hubProxy.Invoke("DisplayMessageGroup", "CommonClientGroup", "Hello Group Members!").Wait(); string leaveGroupResponse = hubProxy.Invoke<string>("LeaveGroup", hubConnection.ConnectionId, "CommonClientGroup").Result; hubConnection.TraceWriter.WriteLine("leaveGroupResponse={0}", leaveGroupResponse); hubProxy.Invoke("DisplayMessageGroup", "CommonClientGroup", "Hello Group Members! (caller should not see this message)").Wait(); hubProxy.Invoke("DisplayMessageCaller", "Hello Caller again!").Wait(); }
private static void Connect() { analyticsWebsiteExceptionHubConnection = new HubConnection(analyticsWebsiteConnectionUrl); analyticsWebsiteProxy = analyticsWebsiteExceptionHubConnection.CreateHubProxy("ExceptionHub"); analyticsWebsiteExceptionHubConnection.Start().Wait(); analyticsWebsiteConnected = true; }
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 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"); }
private static void ConnectEventHub() { hubConnection = new HubConnection(connectionUrl); proxy = hubConnection.CreateHubProxy("EventHub"); hubConnection.Start().Wait(); connected = true; }
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(); }
public void ConnectToServer(string url) { this.url = url; hubConnection = new HubConnection(url); hubProxy = hubConnection.CreateHubProxy("SoftNodesHub"); bool isConnected=false; while (!isConnected) { try { hubConnection.Start().Wait(); hubConnection.Closed += OnHubConnectionClosed; hubProxy.On<Message>("ReceiveMessage", ReceiveMessage); isConnected = true; if (OnConnected != null) OnConnected(); } catch (Exception e) { if (OnConnectionFailed != null) OnConnectionFailed(e.Message); } } }
public async Task WebSocketSendReceiveTest() { const int MessageCount = 3; var sentMessages = new List<string>(); var receivedMessages = new List<string>(); using (var hubConnection = new HubConnection(HubUrl)) { var wh = new ManualResetEventSlim(); var proxy = hubConnection.CreateHubProxy("StoreWebSocketTestHub"); proxy.On<string>("echo", m => { receivedMessages.Add(m); if (receivedMessages.Count == MessageCount) { wh.Set(); } }); await hubConnection.Start(new WebSocketTransport()); for (var i = 0; i < MessageCount; i++) { var message = "MyMessage" + i; await proxy.Invoke("Echo", message); sentMessages.Add(message); } await Task.Run(() => wh.Wait(5000)); } Assert.Equal(sentMessages, receivedMessages); }
private async void Init() { hubConnection = new HubConnection("http://localhost:5225"); proxy = hubConnection.CreateHubProxy("MyHub"); await hubConnection.Start(); proxy.On<string>("executeCommand", (data) => { Debug.WriteLine(data); // var message = Newtonsoft.Json.JsonConvert.DeserializeObject<Message>(data.ToString()); }); qmhubConnection = new HubConnection("http://quantifymewebhub.azurewebsites.net/"); qmproxy = qmhubConnection.CreateHubProxy("QuantifyMeHub"); await qmhubConnection.Start(); qmproxy.On<string,string>("send", (name, data) => { Debug.WriteLine(data); var message = new Message { Source = "RemoteUWP", Action = "UpdateData", Value = data }; proxy.Invoke("Send", Newtonsoft.Json.JsonConvert.SerializeObject(message)); }); }
public MainWindow() { InitializeComponent(); connection = new HubConnection(@"http://iskenxan-001-site1.btempurl.com/signalr"); myHub = connection.CreateHubProxy("ChatHub"); UserNameTextBox.Focus(); }
public LiveTraceSignalRProvider(string hubUrl) { _hubConnection = new HubConnection(hubUrl); _hubConnection.Credentials = CredentialCache.DefaultCredentials; _hubProxy = _hubConnection.CreateHubProxy("LiveTraceSignalRHub"); _hubConnection.Start().Wait(); }
public StockTraderHubGateway(IEventAggregator eventAggregator) { this.eventAggregator = eventAggregator; this.connection = new HubConnection("http://localhost:14635"); this.proxy = this.connection.CreateHubProxy("trader"); this.hubEventsListener = new HubEventsListener(this.eventAggregator, this.proxy); this.userEventsListener = new UserEventsListener(this.eventAggregator, this.proxy); }
static void Main(string[] arguments) { var connection = new HubConnection("http://modulebuddies.azurewebsites.net/TestDraw"); // Since we are client, we must specify a URL var shapeHub = connection.CreateHubProxy("shape"); //or Kh2ndcore.CollaborativeWhiteBoard.ShapeHub // Register thge events that we are intereted in - similar to the JS client creating methods to be called back upon by the server shapeHub.On<string, int, int, int, int, string>("lineDrawn", (cid, fromX, fromY, toX, toY, color) => { Console.WriteLine("lineDrawn => Connection Id: {0}, FromX:{1}, FromY: {2}, ToX:{3}, ToY: {4}, Color: {5}", cid, fromX, fromY, toX, toY, color); }); shapeHub.On<string, int, int, string, string>("textTyped", (cid, x, y, text, color) => { Console.WriteLine("textTyped => Connection Id: {0}, x:{1}, y: {2}, text:{3}, Color: {4}", cid, x, y, text, color); }); shapeHub.On("canvasCleared", () => Console.WriteLine("Canvas Cleared!!!")); shapeHub.On<int>("connectionsCountUpdate", (c) => { Console.WriteLine("connectionsCountUpdate => Count: {0}", c); }); shapeHub.On<List<string>>("usersUpdated", (users) => { foreach (string user in users) Console.WriteLine("usersUpdated => User: {0}", user); }); // Make the connection connection.Start().Wait(); // Register the console application with a black color shapeHub.Invoke("registerUser", connection.ConnectionId, "console", "#000000").Wait(); int increment = 10; int fromXPoint = 0; int fromYPoint = 0; int toXPoint = increment; int toYPoint = 0; shapeHub.Invoke("drawLine", connection.ConnectionId, toXPoint, toYPoint, fromXPoint, fromYPoint, "#000000"); for (int i = 0; i < 10; i++) { fromYPoint += increment; toXPoint += increment; toYPoint += increment; shapeHub.Invoke("drawLine", connection.ConnectionId, toXPoint, toYPoint, fromXPoint, fromYPoint, "#000000"); Thread.Sleep(1000); } fromYPoint += (increment * 2); shapeHub.Invoke("typeText", connection.ConnectionId, fromXPoint, fromYPoint, "Hello from the console app!", "#000000"); connection.Stop(); Console.Read(); }
private void OnStartConnect(object state) { string url = state as string; this.hubConnection = new HubConnection(url); this.hub = this.hubConnection.CreateHubProxy("RobotSignalHub"); this.hubConnection.Start(); this.hubConnection.StateChanged += OnHubConnectionStateChanged; }
public override void Initialize() { for (int i = 0; i < Connections; i++) { _connections[i] = new HubConnection(RunData.Url); } base.Initialize(); }
static void Main(string[] args) { Console.WriteLine("Client Starting..."); var hubConnection = new HubConnection("http://localhost:6666"); var hubProxy = hubConnection.CreateHubProxy("SimpleHub"); HashSet<Data> received = new HashSet<Data>(); HashSet<Data> requested = new HashSet<Data>(); object locker = new object(); hubProxy.On<Data>("Respond", s => { lock (locker) { received.Add(s); Console.WriteLine("Request: {0}\t\t Response: {1}", requested.Count, received.Count); } }); hubConnection.Start().Wait(); Console.WriteLine("Client Started"); var totalRequestsToMake = 5000; Console.WriteLine("Making {0} Requests...", totalRequestsToMake); for (int i = 0; i < totalRequestsToMake; i++) { var s = Guid.NewGuid().ToString(); requested.Add(new Data{String = s, Number = i}); } foreach (var r in requested) { if (hubConnection.State != ConnectionState.Connected) { hubConnection.Start().Wait(); } hubProxy.Invoke("Request", r) .ContinueWith(task => { if (!task.IsFaulted) return; Console.WriteLine("Error making Request: {0}", r.Number); foreach (var innerException in task.Exception.InnerExceptions) { Console.WriteLine("\t{0}", innerException); } } ); } Console.WriteLine("Requests Complete"); Console.ReadLine(); }
private void OnStopButtonClick(object sender, RoutedEventArgs e) { this.hubConnection.Disconnect(); this.hubConnection.StateChanged -= OnHubConnectionStateChanged; this.hub = null; this.hubConnection = null; this.startButton.IsEnabled = true; this.stopButton.IsEnabled = false; }
private async Task SetupSignalRConnection() { _connection = new HubConnection("http://pbclone.azurewebsites.net/"); _connection.StateChanged += ConnectionOnStateChanged; _mainHub = _connection.CreateHubProxy("imghub"); await _connection.Start(); _mainHub.Invoke("Create", _guid); }
public ChatHub(string url) { _connection=new HubConnection(url); _proxy = _connection.CreateHubProxy("chat"); _proxy.On("Recieve", (string message) => OnRecieved(message)); _connection.Start(); }
public MessageHubProxy() { var hubConnection = new HubConnection("http://localhost:8001/"); messageHub = hubConnection.CreateHubProxy("messageHub"); hubConnection.StateChanged += change => Console.WriteLine(change.OldState + " => " + change.NewState); messageHub.On<string>("Send", s => Console.WriteLine("Some client used send -> {0}", s)); hubConnection.Start().Wait(); }
public IHubProxy Create(string hubUrl, Action<IHubConnection> configureConnection, Action<IHubProxy> onStarted) { var connection = new HubConnection(hubUrl); if (configureConnection != null) configureConnection(connection); var proxy = connection.CreateHubProxy("EventAggregatorProxyHub"); connection.Start().ContinueWith(o => onStarted(proxy)); return proxy; }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) { var uiContext = SynchronizationContext.Current; datagrid.ItemsSource = sd.Collection; //Set connection var connection = new HubConnection("http://localhost:60599/"); //Make proxy to hub based on hub name on server MyHub = connection.CreateHubProxy("RealTimeHub"); //Start connection //var ollection = new ItemCollection // { // new Item // { // SettingsName = "BidRecommendationService", // SettingsValue = "{IsStacked=False}" // } // }; MyHub.On <string>("addMessage", param => { //Console.WriteLine(param); param = param.Replace("Server:", ""); var keyValue = param.Split(':'); var findIndex = sd.Collection.ToList().FindIndex(v => v.SettingsName == keyValue[0]); if (findIndex > -1) { //App.Current.Dispatcher.Invoke((Action)delegate // <--- HERE //{ try { Task.Run(() => { App.Current.Dispatcher.BeginInvoke((Action) delegate { var item = sd.Collection.ElementAt(findIndex).SettingsValue = keyValue[1]; sd.Collection.RemoveAt(findIndex); sd.Collection.Insert(findIndex, new Item { SettingsName = keyValue[0], SettingsValue = keyValue[1] }); }); }); }catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } //}); } else if (findIndex == -1 && param.Contains(':')) { App.Current.Dispatcher.Invoke((Action) delegate // <--- HERE { sd.Collection.Add(new Item { SettingsName = keyValue[0], SettingsValue = keyValue[1] }); }); } sd.DynamicText += param + Environment.NewLine; //setting. }); var isConnected = false; while (!isConnected) { connection.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException()); sd.ConnectionStatus = "There was an error opening the connection"; Thread.Sleep(2000); } else { isConnected = true; sd.ConnectionStatus = "Connected!"; } }).Wait(); } }
private async void InitializeNotifications() { _hubConnection = new HubConnection(CommonAppSettings.SignalRUrl); _proxy = _hubConnection.CreateHubProxy("MyShuttleHub"); await _hubConnection.Start(); }
public void Handle(HubConnection connection, IMediator mediator) { HandleRequest <GetContactListRequest, GetContactListQuery>(connection, mediator); }
public void Handle(HubConnection connection, IMediator mediator) { HandleRequest <DeleteWalletRequest, DeleteWalletCmd>(connection, mediator); }
public async Task <ChannelReader <int> > StreamDuplexTwoChannel(ChannelReader <int> channel) { return(await HubConnection.StreamAsChannelAsync <int>("DuplexTwoChannel", channel)); }
private void Hub_Redirected(HubConnection hub, Uri oldUri, Uri newUri) { AddText(string.Format("Hub connection redirected to '<color=green>{0}</color>' with Access Token: '<color=green>{1}</color>'", hub.Uri, hub.NegotiationResult.AccessToken)); }
private void RegisterMessageHandlers() { // TODO: Remove possibility for circular dependencies in the future // by emitting these events so other services can listen for them. HubConnection.On("Chat", async(string senderName, string message, string orgName, bool disconnected, string senderConnectionID) => { if (!IsServerVerified) { Logger.Write("Chat attempted before server was verified.", EventType.Warning); return; } await ChatService.SendMessage(senderName, message, orgName, disconnected, senderConnectionID, HubConnection); }); HubConnection.On("DownloadFile", async(string filePath, string senderConnectionID) => { if (!IsServerVerified) { Logger.Write("File download attempted before server was verified.", EventType.Warning); return; } filePath = filePath.Replace("\"", ""); if (!File.Exists(filePath)) { await HubConnection.SendAsync("DisplayMessage", "File not found on remote device.", "File not found.", senderConnectionID); return; } using var wc = new WebClient(); var lastProgressPercent = 0; wc.UploadProgressChanged += async(sender, args) => { if (args.ProgressPercentage > lastProgressPercent) { lastProgressPercent = args.ProgressPercentage; await HubConnection.SendAsync("DownloadFileProgress", lastProgressPercent, senderConnectionID); } }; try { var response = await wc.UploadFileTaskAsync($"{ConnectionInfo.Host}/API/FileSharing/", filePath); var fileIDs = JsonSerializer.Deserialize <string[]>(Encoding.UTF8.GetString(response)); await HubConnection.SendAsync("DownloadFile", fileIDs[0], senderConnectionID); } catch (Exception ex) { Logger.Write(ex); await HubConnection.SendAsync("DisplayMessage", "Error occurred while uploading file from remote computer.", "Upload error.", senderConnectionID); } }); HubConnection.On("ChangeWindowsSession", async(string serviceID, string viewerID, int targetSessionID) => { if (!IsServerVerified) { Logger.Write("Session change attempted before server was verified.", EventType.Warning); return; } await AppLauncher.RestartScreenCaster(new List <string>() { viewerID }, serviceID, viewerID, HubConnection, targetSessionID); }); HubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) => { if (!IsServerVerified) { Logger.Write($"Command attempted before server was verified. Mode: {mode}. Command: {command}. Sender: {senderConnectionID}", EventType.Warning); return; } await CommandExecutor.ExecuteCommand(mode, command, commandID, senderConnectionID, HubConnection); })); HubConnection.On("ExecuteCommandFromApi", (async(string mode, string requestID, string command, string commandID, string senderUserName) => { if (!IsServerVerified) { Logger.Write($"Command attempted before server was verified. Mode: {mode}. Command: {command}. Sender: {senderUserName}", EventType.Warning); return; } await CommandExecutor.ExecuteCommandFromApi(mode, requestID, command, commandID, senderUserName, HubConnection); })); HubConnection.On("UploadFiles", async(string transferID, List <string> fileIDs, string requesterID) => { if (!IsServerVerified) { Logger.Write("File upload attempted before server was verified.", EventType.Warning); return; } Logger.Write($"File upload started by {requesterID}."); var sharedFilePath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName; foreach (var fileID in fileIDs) { var url = $"{ConnectionInfo.Host}/API/FileSharing/{fileID}"; var wr = WebRequest.CreateHttp(url); var response = await wr.GetResponseAsync(); var cd = response.Headers["Content-Disposition"]; var filename = cd .Split(";") .FirstOrDefault(x => x.Trim() .StartsWith("filename")) .Split("=")[1]; var legalChars = filename.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y)); filename = new string(legalChars.ToArray()); using var rs = response.GetResponseStream(); using var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create); rs.CopyTo(fs); } await HubConnection.SendAsync("TransferCompleted", transferID, requesterID); }); HubConnection.On("DeployScript", async(string mode, string fileID, string commandResultID, string requesterID) => { if (!IsServerVerified) { Logger.Write($"Script deploy attempted before server was verified. Mode: {mode}. File ID: {fileID}. Sender: {requesterID}", EventType.Warning); return; } await ScriptRunner.RunScript(mode, fileID, commandResultID, requesterID, HubConnection); }); HubConnection.On("UninstallClient", () => { Uninstaller.UninstallAgent(); }); HubConnection.On("RemoteControl", async(string requesterID, string serviceID) => { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified.", EventType.Warning); return; } await AppLauncher.LaunchRemoteControl(-1, requesterID, serviceID, HubConnection); }); HubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) => { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified.", EventType.Warning); return; } await AppLauncher.RestartScreenCaster(viewerIDs, serviceID, requesterID, HubConnection); }); HubConnection.On("CtrlAltDel", () => { if (!IsServerVerified) { Logger.Write("CtrlAltDel attempted before server was verified.", EventType.Warning); return; } User32.SendSAS(false); }); HubConnection.On("ServerVerificationToken", (string verificationToken) => { if (verificationToken == ConnectionInfo.ServerVerificationToken) { IsServerVerified = true; } else { Logger.Write($"Server sent an incorrect verification token. Token Sent: {verificationToken}.", EventType.Warning); return; } }); }
public void Handle(HubConnection connection, IMediator mediator) { HandleRequest <CreateContactRequest, CreateContactCmd>(connection, mediator); }
public SensiConnection() { Trace.WriteLine("SensiConnection ctor"); this._cookieJar = new CookieContainer(); this._hubConnection = new HubConnection(_urlBase + "realtime", false); this._hubConnection.CookieContainer = this._cookieJar; this._hubProxy = this._hubConnection.CreateHubProxy("thermostat-v1"); this._subscriptions = new List <string>(); this._hubConnection.StateChanged += (state) => { Debug.WriteLine($"State Changed from {state.OldState} to {state.NewState}"); }; this._hubConnection.ConnectionSlow += () => { Debug.WriteLine("Connection Slow"); }; this._hubConnection.Reconnected += () => { Debug.WriteLine("Reconnected"); }; this._hubConnection.Reconnecting += () => { Debug.WriteLine("Reconnecting"); }; this._hubConnection.Error += async(ex) => { Trace.WriteLine(ex, "HubConnection Error"); if (ex is System.Net.WebException) { if (((System.Net.WebException)ex).Status == WebExceptionStatus.ProtocolError) { var response = ((System.Net.WebException)ex).Response as HttpWebResponse; if (response != null && ( response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.InternalServerError) ) { Trace.WriteLine("Restarting Realtime due to WebExpection"); while (await this.BeginRealtime() == false) { Trace.WriteLine("Not Connected, Delaying..."); this.StopRealtime(); await Task.Delay(5000); } foreach (var sub in _subscriptions) { Trace.WriteLine("Attempt Re-Subscription for " + sub); this.Subscribe(sub).Wait(); } return; } } } else if (ex is System.Net.Sockets.SocketException) { Trace.WriteLine("Restarting Realtime due to SocketException"); while (await this.BeginRealtime() == false) { Trace.WriteLine("Not Connected, Delaying..."); this.StopRealtime(); await Task.Delay(5000); } foreach (var sub in _subscriptions) { Trace.WriteLine("Attempt Re-Subscription for " + sub); this.Subscribe(sub).Wait(); } return; } }; this._hubConnection.Received += (data) => { Debug.WriteLine("Data Received"); }; this._hubProxy.On <object>("initalized", (data) => { Trace.WriteLine(data, "Initalized"); }); this._hubProxy.On <object, object>("online", (icd, data) => { //Trace.WriteLine(Environment.NewLine + data, $"Received Online Message for ICD [{icd}]"); Trace.WriteLine($"Received Online Message for ICD [{icd}]"); this.LastUpdateReceived = DateTime.Now; try { var msg = JsonConvert.DeserializeObject <OnlineResponse>(data.ToString()); var args = (ThermostatOnlineEventArgs)msg; args.Icd = icd.ToString(); ThermostatOnline?.Invoke(this, args); } catch (Exception ex) { Trace.WriteLine(ex); } }); this._hubProxy.On <object, object>("update", (icd, data) => { //Trace.WriteLine(Environment.NewLine + data, $"Received Update Message for ICD [{icd}]"); Trace.WriteLine($"Received Update Message for ICD [{icd}]"); this.LastUpdateReceived = DateTime.Now; OnlineResponse msg = null; try { msg = JsonConvert.DeserializeObject <OnlineResponse>(data.ToString()); } catch (Exception ex) { Trace.WriteLine(ex); } if (msg != null) { if (msg != null && msg.OperationalStatus != null) { OperationalStatusUpdated?.Invoke(this, new OperationalStatusUpdatedEventArgs { Icd = icd.ToString(), OperationalStatus = msg.OperationalStatus }); } if (msg != null && msg.EnvironmentControls != null) { EnvironmentalControlsUpdated?.Invoke(this, new EnvironmentalControlsUpdatedEventArgs { Icd = icd.ToString(), EnvironmentControls = msg.EnvironmentControls }); } if (msg != null && msg.Capabilities != null) { CapabilitiesUpdated?.Invoke(this, new CapabilitiesUpdatedEventArgs { Icd = icd.ToString(), Capabilities = msg.Capabilities }); } if (msg != null && msg.Settings != null) { SettingsUpdated?.Invoke(this, new SettingsUpdatedEventArgs { Icd = icd.ToString(), Settings = msg.Settings }); } if (msg != null && msg.Product != null) { ProductUpdated?.Invoke(this, new ProductUpdatedEventArgs { Icd = icd.ToString(), Product = msg.Product }); } } }); this._hubProxy.On <object, object>("offline", (icd, data) => { //Trace.WriteLine(Environment.NewLine + data, $"Received Offline Message for ICD [{icd}]"); Trace.WriteLine($"Received Offline Message for ICD [{icd}]"); this.LastUpdateReceived = DateTime.Now; }); }
public Instance(HubConnection hubConnection, IHubProxy hubProxy) { _hubConnection = hubConnection; _hubProxy = hubProxy; }
public async Task Handler(string message, ConcurrentDictionary <string, InvocationRequestCallBack <object> > requestCallBacks, ConcurrentDictionary <string, InvocationHandlerList> invocationHandlers, HubConnection hubConnection) { _logger.LogDebug($"开始处理CloseMessage, Message:{message}"); var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var BasicInvocationMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <CloseWithError>(message, settings); var error = "服务器关闭了连接"; if (!string.IsNullOrEmpty(BasicInvocationMessage.Error)) { error = $"服务器关闭了连接,message:{BasicInvocationMessage.Error}"; } _logger.LogError(error); await hubConnection.CloseAsync(error); }
public CharacterMoveTest() { _connection = new HubConnection("http://localhost:8080"); }
public static Task SendAsync(this HubConnection hubConnection, string methodName, object?arg1, object?arg2, object?arg3, object?arg4, CancellationToken cancellationToken = default) { return(hubConnection.SendCoreAsync(methodName, new[] { arg1, arg2, arg3, arg4 }, cancellationToken)); }
/// <summary> /// Called when an unrecoverable error happen. After this event the hub will not send or receive any messages. /// </summary> private void Hub_OnError(HubConnection hub, string error) { AddText(string.Format("Hub Error: <color=red>{0}</color>", error)); SetButtons(true, false); }
private List <HubConnection> Create(int startCliIndex, int endCliIndex, string url, string transportTypeName = "Websockets", string hubProtocol = "json") { Util.Log($"transport type: {transportTypeName}"); var transportType = HttpTransportType.WebSockets; switch (transportTypeName) { case "LongPolling": transportType = HttpTransportType.LongPolling; break; case "ServerSentEvents": transportType = HttpTransportType.ServerSentEvents; break; case "None": transportType = HttpTransportType.None; break; default: transportType = HttpTransportType.WebSockets; break; } Util.Log($"Connection string: {url}"); var serviceUtils = new ServiceUtils(url); _tk.State = Stat.Types.State.HubconnCreating; var connections = new List <HubConnection>(endCliIndex - startCliIndex); for (var i = startCliIndex; i < endCliIndex; i++) { var serviceUrl = serviceUtils.GetClientUrl(); var userId = $"{ServiceUtils.ClientUserIdPrefix}{i}"; var cookies = new CookieContainer(); var httpClientHandler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, CookieContainer = cookies, }; var hubConnectionBuilder = new HubConnectionBuilder() /* TODO. Console log is important for finding errors. * But if every connection enables it, there will be thousands of * 'Console logger queue processing thread' which degrade the system * response, and bring issues to counters statistic. * Temporarily, we disable it. We need to find the best way * to enable it. */ //.ConfigureLogging(logging => //{ // logging.AddConsole(); // logging.SetMinimumLevel(LogLevel.Warning); //}) .WithUrl(serviceUrl, httpConnectionOptions => { httpConnectionOptions.HttpMessageHandlerFactory = _ => httpClientHandler; httpConnectionOptions.Transports = transportType; httpConnectionOptions.CloseTimeout = TimeSpan.FromMinutes(100); httpConnectionOptions.Cookies = cookies; httpConnectionOptions.AccessTokenProvider = () => { return(Task.FromResult(serviceUtils.GenerateAccessToken(serviceUrl, userId))); }; }); HubConnection connection = null; switch (hubProtocol) { case "json": connection = hubConnectionBuilder.Build(); break; case "messagepack": connection = hubConnectionBuilder.AddMessagePackProtocol().Build(); break; default: throw new Exception($"{hubProtocol} is invalid."); } connection.Closed += e => { if (_tk.State <= Stat.Types.State.SendComplete && _tk.State >= Stat.Types.State.SendReady) { var error = $"Connection closed early: {e}"; Util.Log(error); } return(Task.CompletedTask); }; connections.Add(connection); } _tk.State = Stat.Types.State.HubconnCreated; return(connections); }
static void Main(string[] args) { Console.WriteLine("Press Enter when the server is ready..."); Console.ReadLine(); Console.Clear(); string url = "http://localhost:8080"; var hubConnection = new HubConnection(url); var hubProxy = hubConnection.CreateHubProxy("EmpireHub"); hubProxy.On("NewEmpire", x => NewEmpire(hubProxy, new Empire() { EGov = x.EGov, Empno = x.Empno, EName = x.EName })); hubProxy.On("EmpireModified", x => EmpireModified(hubProxy, (int)x)); hubProxy.On("EmpireCrushed", x => EmpireCrushed(hubProxy, x)); hubConnection.Start().ContinueWith(x => { if (x.IsFaulted) { Console.WriteLine("ERROR" + x.Exception.GetBaseException()); } else { Console.WriteLine("CONNECTED"); } }).Wait(); var task = hubProxy.Invoke <IEnumerable <string> >("GetEmpireNames"); task.Wait(); Console.WriteLine("The names of the current empires:"); foreach (var k in task.Result) { Console.WriteLine(k); } Console.WriteLine("\n"); task = hubProxy.Invoke <IEnumerable <string> >("GetGovernmentNames"); task.Wait(); Console.WriteLine("Government types:"); foreach (var k in task.Result) { Console.WriteLine(k); } Console.WriteLine("\n"); /* * nem akarom (ennél is jobban) restruktúrálni a kódot, hogy valamennyi sorrendiség még legyen azért... * egy kis delay pont elégnek tűnik, a lockkal végképp... * de lehet egy lassabb gépen (vagy éppen gyorsabb gépen?) nem elég... */ var j = new Empire() { EName = "Federation Late to the Game", EGov = "Prethoryn food", Empno = 21 }; hubProxy.Invoke("AddEmpire", j).Wait(); Task.Delay(20).Wait(); hubProxy.Invoke("ModifyEmpireGovernment", 21, "Human Federation").Wait(); Task.Delay(20).Wait(); hubProxy.Invoke("RemoveEmpire", 21).Wait(); Task.Delay(20).Wait(); lock (consoleLock) Console.WriteLine("Press Enter to stop..."); Console.ReadLine(); hubConnection.Stop(); }
public static Task SendAsync(this HubConnection hubConnection, string methodName, CancellationToken cancellationToken = default) { return(hubConnection.SendCoreAsync(methodName, Array.Empty <object>(), cancellationToken)); }
protected override void AfterSubscribe(HubConnection hubConnection) { hubConnection.On <IApplicationEvent>("IApplicationEvent", OnApplicationEvent); }
public AlarmNotificationClient(HubConnection hubConnection) { _whenMessageReceivedSubject = new Subject <AlarmNotification>(); this.hubConnection = hubConnection; }
private static void RegisterMessageHandlers(HubConnection hubConnection) { hubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) => { await ExecuteCommand(mode, command, commandID, senderConnectionID); })); hubConnection.On("TransferFiles", async(string transferID, List <string> fileIDs, string requesterID) => { Logger.Write($"File transfer started by {requesterID}."); var connectionInfo = Utilities.GetConnectionInfo(); var sharedFilePath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName; foreach (var fileID in fileIDs) { var url = $"{connectionInfo.Host}/API/FileSharing/{fileID}"; var wr = WebRequest.CreateHttp(url); var response = await wr.GetResponseAsync(); var cd = response.Headers["Content-Disposition"]; var filename = cd .Split(";") .FirstOrDefault(x => x.Trim() .StartsWith("filename")) .Split("=")[1]; var legalChars = filename.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y)); filename = new string(legalChars.ToArray()); using (var rs = response.GetResponseStream()) { using (var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create)) { rs.CopyTo(fs); } } } await HubConnection.InvokeAsync("TransferCompleted", transferID, requesterID); }); hubConnection.On("DeployScript", async(string mode, string fileID, string commandContextID, string requesterID) => { var connectionInfo = Utilities.GetConnectionInfo(); var sharedFilePath = Directory.CreateDirectory(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Remotely", "SharedFiles" )).FullName; var webClient = new WebClient(); var url = $"{connectionInfo.Host}/API/FileSharing/{fileID}"; var wr = WebRequest.CreateHttp(url); var response = await wr.GetResponseAsync(); var cd = response.Headers["Content-Disposition"]; var filename = cd.Split(";").FirstOrDefault(x => x.Trim().StartsWith("filename")).Split("=")[1]; using (var rs = response.GetResponseStream()) { using (var sr = new StreamReader(rs)) { var result = await sr.ReadToEndAsync(); await ExecuteCommand(mode, result, commandContextID, requesterID); } } }); hubConnection.On("UninstallClient", () => { Uninstaller.UninstallAgent(); }); hubConnection.On("RemoteControl", async(string requesterID, string serviceID) => { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified."); Uninstaller.UninstallAgent(); return; } try { var rcBinaryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ScreenCast", OSUtils.ScreenCastExecutableFileName); if (!File.Exists(rcBinaryPath)) { await hubConnection.InvokeAsync("DisplayMessage", "Remote control executable not found on target device.", "Executable not found on device.", requesterID); return; } // Start ScreenCast. await hubConnection.InvokeAsync("DisplayMessage", $"Starting remote control...", "Starting remote control.", requesterID); if (OSUtils.IsWindows) { if (Program.IsDebug) { Process.Start(rcBinaryPath, $"-mode Unattended -requester {requesterID} -serviceid {serviceID} -deviceid {ConnectionInfo.DeviceID} -host {Utilities.GetConnectionInfo().Host} -desktop default"); } else { var result = Win32Interop.OpenInteractiveProcess(rcBinaryPath + $" -mode Unattended -requester {requesterID} -serviceid {serviceID} -deviceid {ConnectionInfo.DeviceID} -host {Utilities.GetConnectionInfo().Host} -desktop default", "default", true, out _); if (!result) { await hubConnection.InvokeAsync("DisplayMessage", "Remote control failed to start on target device.", "Failed to start remote control.", requesterID); } } } else if (OSUtils.IsLinux) { var users = OSUtils.StartProcessWithResults("users", ""); var username = users?.Split()?.FirstOrDefault()?.Trim(); var homeDir = OSUtils.StartProcessWithResults("sudo", $"-u {username} env | grep HOME")?.Split('=')?.Last(); var psi = new ProcessStartInfo() { FileName = "sudo", Arguments = $"-u {username} {rcBinaryPath} -mode Unattended -requester {requesterID} -serviceid {serviceID} -deviceid {ConnectionInfo.DeviceID} -host {Utilities.GetConnectionInfo().Host} -desktop default & disown" }; psi.Environment.Add("DISPLAY", ":0"); psi.Environment.Add("XAUTHORITY", $"{homeDir}/.Xauthority"); var casterProc = Process.Start(psi); casterProc.WaitForExit(); } } catch (Exception ex) { Logger.Write(ex); await hubConnection.InvokeAsync("DisplayMessage", "Remote control failed to start on target device.", "Failed to start remote control.", requesterID); throw; } }); hubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) => { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified."); Uninstaller.UninstallAgent(); return; } try { var rcBinaryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ScreenCast", OSUtils.ScreenCastExecutableFileName); // Start ScreenCast. if (OSUtils.IsWindows) { Logger.Write("Restarting screen caster."); if (Program.IsDebug) { var proc = Process.Start(rcBinaryPath, $"-mode Unattended -requester {requesterID} -serviceid {serviceID} -deviceid {ConnectionInfo.DeviceID} -host {Utilities.GetConnectionInfo().Host} -relaunch true -desktop default -viewers {String.Join(",", viewerIDs)}"); var stopwatch = Stopwatch.StartNew(); while (stopwatch.Elapsed.TotalSeconds < 10) { await Task.Delay(250); if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(rcBinaryPath))?.Where(x => x.Id == proc.Id)?.Count() > 0 != true) { Logger.Write("Restarting screen caster after failed relaunch."); } } } else { var result = Win32Interop.OpenInteractiveProcess(rcBinaryPath + $" -mode Unattended -requester {requesterID} -serviceid {serviceID} -deviceid {ConnectionInfo.DeviceID} -host {Utilities.GetConnectionInfo().Host} -relaunch true -desktop default -viewers {String.Join(",", viewerIDs)}", "default", true, out var procInfo); if (result) { // This relaunch might have been prompted by a user logging out, which would close // the screencaster process. In that scenario, the relaunched process can get closed again // while the Windows sign-out process is still occurring. We'll wait a bit to make sure the // relaunched process is still running. If not, launch again. var stopwatch = Stopwatch.StartNew(); while (stopwatch.Elapsed.TotalSeconds < 10) { await Task.Delay(250); if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(rcBinaryPath))?.Where(x => x.Id == procInfo.dwProcessId)?.Count() > 0 != true) { Logger.Write("Restarting screen caster after failed relaunch."); result = Win32Interop.OpenInteractiveProcess(rcBinaryPath + $" -mode Unattended -requester {requesterID} -serviceid {serviceID} -deviceid {ConnectionInfo.DeviceID} -host {Utilities.GetConnectionInfo().Host} -relaunch true -desktop default -viewers {String.Join(",", viewerIDs)}", "default", true, out procInfo); } } } if (!result) { Logger.Write("Failed to relaunch screen caster."); await hubConnection.InvokeAsync("SendConnectionFailedToViewers", viewerIDs); await hubConnection.InvokeAsync("DisplayMessage", "Remote control failed to start on target device.", "Failed to start remote control.", requesterID); } } } else if (OSUtils.IsLinux) { var users = OSUtils.StartProcessWithResults("users", ""); var username = users?.Split()?.FirstOrDefault()?.Trim(); var homeDir = OSUtils.StartProcessWithResults("sudo", $"-u {username} env | grep HOME")?.Split('=')?.Last(); var psi = new ProcessStartInfo() { FileName = "sudo", Arguments = $"-u {username} {rcBinaryPath} -mode Unattended -requester {requesterID} -serviceid {serviceID} -deviceid {ConnectionInfo.DeviceID} -host {Utilities.GetConnectionInfo().Host} -relaunch true -desktop default -viewers {String.Join(",", viewerIDs)} & disown" }; psi.Environment.Add("DISPLAY", ":0"); psi.Environment.Add("XAUTHORITY", $"{homeDir}/.Xauthority"); var casterProc = Process.Start(psi); casterProc.WaitForExit(); } } catch (Exception ex) { await hubConnection.InvokeAsync("SendConnectionFailedToViewers", viewerIDs); Logger.Write(ex); throw; } }); hubConnection.On("CtrlAltDel", () => { User32.SendSAS(false); }); hubConnection.On("ServerVerificationToken", (string verificationToken) => { if (verificationToken == Utilities.GetConnectionInfo().ServerVerificationToken) { IsServerVerified = true; if (!Program.IsDebug) { Updater.CheckForCoreUpdates(); } } else { Logger.Write($"Server sent an incorrect verification token. Token Sent: {verificationToken}."); Uninstaller.UninstallAgent(); return; } }); }
public async Task SendHeartbeat() { var currentInfo = await DeviceInformation.Create(ConnectionInfo.DeviceID, ConnectionInfo.OrganizationID); await HubConnection.SendAsync("DeviceHeartbeat", currentInfo); }
public async Task SendMessage(Message message, HubConnection hubConnection) { await hubConnection.SendAsync(SignalRMehod.SendMessage, message); ChangePost?.Invoke(); }
public IAsyncEnumerable <int> StreamDuplexTwo(IAsyncEnumerable <int> stream) { return(HubConnection.StreamAsync <int>("DuplexTwo", stream)); }
public async Task <TResult> InvokeAsync <TResult>(Expression <Func <IMinerHub, Task <TResult> > > sendFunction) { var methodCallExpression = (MethodCallExpression)sendFunction.Body; return(await HubConnection.InvokeCoreAsync <TResult>(methodCallExpression.Method.Name, methodCallExpression.Arguments.Select(a => Expression.Lambda(a).Compile().DynamicInvoke()).ToArray())); }
public HubConnectionWrapperOld(string uri) { _wrapped = new HubConnection(uri); }
protected override void BeforeUnsubscribe(HubConnection hubConnection) { hubConnection.Remove("IApplicationEvent"); }
/// <summary> /// This is called when the hub is closed after a StartClose() call. /// </summary> private void Hub_OnClosed(HubConnection hub) { AddText("Hub Closed"); SetButtons(true, false); }
public TradeRateHubProxy(HubConnection connection) : base(connection, "TradeRateMessageHub") { }
/// <summary> /// Start the hub connection - populate FunctionNamesToFullNames first /// </summary> /// <returns></returns> public async Task StartAsync() { // stop any previous hub connection hubConnection?.Stop(); hubConnection?.Dispose(); // make a new hub connection hubConnection = new HubConnection(ConnectionUrl, false); hubConnection.Closed += SocketClosed; #if DEBUG //hubConnection.TraceLevel = TraceLevels.All; //hubConnection.TraceWriter = Console.Out; #endif hubProxy = hubConnection.CreateHubProxy(HubName); if (hubProxy == null) { throw new APIException("CreateHubProxy - proxy is null, this should never happen"); } // assign callbacks for events foreach (string key in FunctionNamesToFullNames.Keys) { hubProxy.On(key, async(string data) => await HandleResponse(key, data)); } // create a custom transport, the default transport is really buggy DefaultHttpClient client = new DefaultHttpClient(); customTransport = new WebsocketCustomTransport(client, ConnectInterval, KeepAlive); var autoTransport = new AutoTransport(client, new IClientTransport[] { customTransport }); hubConnection.TransportConnectTimeout = hubConnection.DeadlockErrorTimeout = TimeSpan.FromSeconds(10.0); // setup connect event customTransport.WebSocket.Connected += async(ws) => { try { SignalrSocketConnection[] socketsCopy; lock (sockets) { socketsCopy = sockets.ToArray(); } foreach (SignalrSocketConnection socket in socketsCopy) { await socket.InvokeConnected(); } } catch (Exception ex) { Logger.Info(ex.ToString()); } }; // setup disconnect event customTransport.WebSocket.Disconnected += async(ws) => { try { SignalrSocketConnection[] socketsCopy; lock (sockets) { socketsCopy = sockets.ToArray(); } foreach (SignalrSocketConnection socket in socketsCopy) { await socket.InvokeDisconnected(); } } catch (Exception ex) { Logger.Info(ex.ToString()); } try { // tear down the hub connection, we must re-create it whenever a web socket disconnects hubConnection?.Dispose(); } catch (Exception ex) { Logger.Info(ex.ToString()); } }; try { // it's possible for the hub connection to disconnect during this code if connection is crappy // so we simply catch the exception and log an info message, the disconnect/reconnect loop will // catch the close and re-initiate this whole method again await hubConnection.Start(autoTransport); // get list of listeners quickly to limit lock HubListener[] listeners; lock (this.listeners) { listeners = this.listeners.Values.ToArray(); } // re-call the end point to enable messages foreach (var listener in listeners) { foreach (object[] p in listener.Param) { await hubProxy.Invoke <bool>(listener.FunctionFullName, p); } } } catch (Exception ex) { Logger.Info(ex.ToString()); } }
protected async Task BuildHubAsync(string url) { HubConnection = new HubConnectionBuilder().WithUrl(url).Build(); }