2012-08-29 4 views
13

Sto appena iniziando ad esplorare signalR e mi piacerebbe poter inviare messaggi dal server a tutti i client.Come si inviano i messaggi dal server al client utilizzando Hub SignalR

Ecco il mio Hub

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using SignalR; 
using SignalR.Hubs; 
using SignalR.Hosting.Common; 
using SignalR.Hosting.AspNet; 
using System.Threading.Tasks; 

namespace MvcApplication1 
{ 
    public class Chat : Hub 
    { 
     public void Send(String message) 
     { 
      // Call the addMessage methods on all clients 
      Clients.addMessage(message); 
     } 
    } 
} 

Ecco il mio cliente Pagina

 <script type="text/javascript"> 

     $(function() { 

      //Proxy created on the fly 
      var chat = $.connection.chat; 

      // Declare a function on the chat hub so the server can invoke it 
      chat.addMessage = function (message) { 
       $("#messages").append("<li>" + message + "</li>"); 
      }; 

      $("#broadcast").click(function() { 
       // call the chat method on the server 
       chat.send($("#msg").val()); 
      }); 

      $.connection.hub.start(); 
     }); 
    </script> 


} 



<input type="text" id="msg" /> 
     <input type="button" id="broadcast" value="broadcast" /> 

     <ul id="messages" class="round"> 


     </ul> 

Questo tutto funziona perfettamente, sono in grado di "chat" tra 2 diversi browser.

La prossima cosa che voglio fare è avviare un messaggio dal server a tutti i client.

Così ho provato questo.

using SignalR; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Optimization; 
using System.Web.Routing; 
using System; 
using System.Web.Routing; 
using SignalR; 
using SignalR.Hubs; 

namespace MvcApplication1 
{ 
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801 

    public class MvcApplication : System.Web.HttpApplication 
    { 
     protected void Application_Start() 
     {    
      var aTimer = new System.Timers.Timer(1000); 

      aTimer.Elapsed += aTimer_Elapsed; 
      aTimer.Interval = 3000; 
      aTimer.Enabled = true; 

      AreaRegistration.RegisterAllAreas(); 

      WebApiConfig.Register(GlobalConfiguration.Configuration); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 
      AuthConfig.RegisterAuth(); 
     } 

     void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
     { 
      var context = GlobalHost.ConnectionManager.GetHubContext<Chat>(); 
      context.Clients.Send("Hello");  
     } 
    } 
} 

Questo non sembra funzionare. Il timer funziona, Il gestore di eventi "aTimer_Elapsed" viene eseguito ogni 3 secondi ma il metodo "Invia" sull'hub della chat non viene mai eseguito.

Qualche idea?

risposta

25

penso che dovrebbe essere

void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    { 
     var context = GlobalHost.ConnectionManager.GetHubContext<Chat>(); 
     context.Clients.All.addMessage("Hello");  
    } 

invece. Con Invia si sta chiamando il metodo utilizzato dal client per chiamare il server ...

+1

E se voglio essere in grado di inviare un messaggio a un cliente specifico, nell'evento che i dati di una tabella nel db vengono modificati, direttamente utilizzando la console DBMS o da un'app desktop o dal mio sito web? –

+0

@MuhammadMamoorKhan Per rivolgersi a un singolo cliente è necessario conoscere l'ID di connessione del cliente. Quindi puoi fare 'GlobalHost.ConnectionManager.GetHubContext () .Clients.Client (connectionId) .addMessage (" qualcosa qui ");' – Corey

0

Sì è necessario impostare quella linea a:

void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    { 
     var context = GlobalHost.ConnectionManager.GetHubContext<Chat>(); 
     context.Clients.All.addMessage("Hello");  
    } 

Tuttavia questo è solo a metà strada e ancora non funzionerà.

Nella tua Js è necessario scrivere:

$(function() { 

//Proxy created on the fly 
var chat = $.connection.chat; 

// Declare a function on the chat hub so the server can invoke it 
chat.client.addMessage = function (message) { 
    $("#messages").append("<li>" + message + "</li>"); 
}; 

$("#broadcast").click(function() { 
    // call the chat method on the server 
    chat.client.addMessage($("#msg").val()); 
}); 

$.connection.hub.start(); 
}); 

ho aggiunto il chat.client questo aggiungerà un metodo hub lato client che il server chiamerà.