SignalR: How to call .Net client method from server?

纵然是瞬间 提交于 2019-11-29 02:29:33

Are you trying to talk to clients outside of Hub? If yes then you will have to get a HubContext outside of Hub. And then you can talk all the clients.

IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();

SignalR Server using Owin Self Host

class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:8081/";

            using (WebApplication.Start<Startup>(url))
            {
                Console.WriteLine("Server running on {0}", url);
                Console.ReadLine();
                IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
                for (int i = 0; i < 100; i++)
                {
                    System.Threading.Thread.Sleep(3000);
                    context.Clients.All.addMessage("Current integer value : " + i.ToString());
                }
                Console.ReadLine();
            }

        }
    }
    class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Turn cross domain on 
            var config = new HubConfiguration { EnableCrossDomain = true };
            config.EnableJavaScriptProxies = true;

            // This will map out to http://localhost:8081/signalr by default
            app.MapHubs(config);
        }
    }
    [HubName("MyHub")]
    public class MyHub : Hub
    {
        public void Chatter(string message)
        {
            Clients.All.addMessage(message);
        }
    }

Signalr Client Console Application consuming Signalr Hubs.

class Program
    {
        static void Main(string[] args)
        {  
            var connection = new HubConnection("http://localhost:8081/");

            var myHub = connection.CreateHubProxy("MyHub");

            connection.Start().Wait();
            // Static type
            myHub.On<string>("addMessage", myString =>
            {
                Console.WriteLine("This is client getting messages from server :{0}", myString);
            });


            myHub.Invoke("Chatter",System.DateTime.Now.ToString()).Wait();


            Console.Read();
        }
    }

To run this code, create two separate applications, then first run server application and then client console application, then just hit key on server console and it will start sending messages to the client.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!