2012-08-29 24 views
13

Estoy empezando a explorar signalR y me gustaría poder enviar mensajes desde el servidor a todos los clientes.Cómo envío mensajes del servidor al cliente usando SignalR Hubs

Aquí es mi 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); 
     } 
    } 
} 

Aquí está mi cliente Página

 <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> 

Todo esto funciona perfectamente, yo soy capaz de "chat" entre los 2 navegadores diferentes.

Lo siguiente que quiero hacer es iniciar un mensaje del servidor a todos los clientes.

Así que probé esto.

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");  
     } 
    } 
} 

Esto no parece funcionar. El temporizador funciona, el manejador de eventos "aTimer_Elapsed" se ejecuta cada 3 segundos, pero el método "Send" en el centro de chat nunca se ejecuta.

¿Alguna idea?

Respuesta

25

creo que debe ser

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

lugar. Con env que está llamando el método utilizado por el cliente para llamar al servidor ...

+1

¿Qué sucede si deseo poder enviar un mensaje a un cliente específico, en el caso de que se cambien los datos en una tabla en la base de datos, ya sea directamente usando la consola DBMS o desde una aplicación de escritorio o mi sitio web? –

+0

@MuhammadMamoorKhan Para dirigirse a un cliente individual, necesita conocer la ID de conexión del cliente. A continuación, puede hacer 'GlobalHost.ConnectionManager.GetHubContext () .Clients.Client (connectionId) .addMessage (" algo aquí ");' – Corey

0

Sí debe establecer esa línea a:

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

Sin embargo esto es sólo la mitad del camino y todavía no funcionará.

En su Js tiene que escribir:

$(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(); 
}); 

que añade el chat.client Esto agregará un método concentrador de cliente que llama al servidor.

Cuestiones relacionadas