locked
Sending message to console from console application and web through SignalR RRS feed

  • Question

  • User1326550230 posted

    I am creating an app which consists of 3 different apps: two console apps and one webapplication. I need to get all my apps communicating with each other. One of my console applications is server app with hub. The other is client. I am able to text from web to server and visa versa. I can text from client to both server and web. But I have absolutely no idea how to text TO client. I've tried like everything. Any help.

    Here's my server:

    using System;
    using Microsoft.AspNet.SignalR;
    using Microsoft.Owin.Hosting;
    using Owin;
    using Microsoft.Owin.Cors;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace SignalRSelfHost
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                string url = "http://localhost:8080";
                using (WebApp.Start(url))
                {
                    Console.Write("Enter your message:");
                    while (true)
                    {
                        string line = Console.ReadLine();
    
                        // Get hub context 
                        IHubContext ctx = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
                        //var myHub = new MyHub();
                        //myHub.Recieve(line);
                        //// call addMessage on all clients of context
                        
                        ctx.Clients.All.addMessage(line);
                    }
                }
            }
        }
    
        class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.UseCors(CorsOptions.AllowAll);
                app.MapSignalR();
            }
        }
    
        public class MyHub : Hub
        {
            public void Send(string message)
            {
                Clients.All.addMessage(message);
            }
    
            public void Recieve(string param)
            {
                Console.WriteLine("Recieved: {0}", param);
            }
        }
    }

    That's web-client:

    <!DOCTYPE html>
    <html>
    <head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
    .container {
    background-color: #99CCFF;
    border: thick solid #808080;
    padding: 20px;
    margin: 20px;
    }
    </style>
    </head>
    <body>
    <div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <ul id="discussion"></ul>
    </div>
    
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.0.3.min.js"></script>
    <script src="http://localhost:8080/signalr/hubs"></script>
    <script type="text/javascript">
    $(function () {
    $.connection.hub.url = "http://localhost:8080/signalr";
    // Declare a proxy to reference the hub.
    var chat = $.connection.myHub;
    
    // Create a function that the hub can call to broadcast messages.
    
    chat.client.addMessage = function (message) {
    // Html encode display message.
    var encodedMsg = $('<div />').text(message).html();
    //Add the message to the page.
    $('#discussion').append('<li><strong>' + "Recieved: "
    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
    };
    
    // Set initial focus to message input box.
    $('#message').focus();
    // Start the connection.
    $.connection.hub.start().done(function () {
    $('#sendmessage').click(function () {
    // Call the Send method on the hub.
    chat.server.send($('#message').val());
    chat.server.recieve($('#message').val());
    // Clear text box and reset focus for next comment.
    $('#message').val('').focus();
    });
    
    });
    });
    </script>
    </body>
    </html>

    and console-client:

    using System;
    using Microsoft.AspNet.SignalR;
    using Microsoft.Owin.Hosting;
    using Owin;
    using Microsoft.Owin.Cors;
    using Microsoft.AspNet.SignalR.Client;
    
    namespace SignalRClient
    {
        class Program
        {
            private static void Main(string[] args)
            {
                var connection = new HubConnection("http://localhost:8080");
                var myHub = connection.CreateHubProxy("MyHub");
                connection.Start().ContinueWith(task => {
                    if (task.IsFaulted)
                    {
                        Console.WriteLine("There was an error opening the connection:{0}",
                                          task.Exception.GetBaseException());
                    }
                Console.Write("Enter your message:");
                while (true)
                {
                    var message = Console.ReadLine();
                    myHub.Invoke("Send", message).ContinueWith(_task =>
                    {
                        if (_task.IsFaulted)
                        {
                            Console.WriteLine("There was an error calling send: {0}", _task.Exception.GetBaseException());
                        }
                    });
                        myHub.Invoke<string>("Recieve", message).Wait();
                        ConsoleKeyInfo ki = Console.ReadKey(true);
                        if (ki.Key == ConsoleKey.X)
                        {
                            break;
                        }
                    }
                }).Wait();
    
                connection.Stop();
            }
        }
    }

    Tuesday, October 9, 2018 9:59 AM

All replies

  • User61956409 posted

    Hi elenakochina11,

    Welcome to ASP.NET forums.

    I am able to text from web to server and visa versa. I can text from client to both server and web. But I have absolutely no idea how to text TO client.

    In you code of console client app, we can find that you just call hub method by using the Invoke method on the Hub proxy, but you do not define method on the client that the server can call.

    To achieve your requirement, please refer to the following sample code.

    Console client app:

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Chat Room Console Client Started!");
    
            var connection = new HubConnection("http://localhost:60416/");
            var myHub = connection.CreateHubProxy("chatHub");
    
    
            connection.Start().ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error opening the connection:{0}",
                                        task.Exception.GetBaseException());
                }
                Console.Write("Enter your message:");
                while (true)
                {
                    var message = Console.ReadLine();
                    myHub.Invoke("Send", "Console Client1", message).ContinueWith(_task =>
                    {
                        if (_task.IsFaulted)
                        {
                            Console.WriteLine("There was an error calling send: {0}", _task.Exception.GetBaseException());
                        }
                    });
    
                    myHub.On<HubMes>("newMessage", mes =>
                    {
                        Console.WriteLine("{0}: {1}", mes.name, mes.message);
                    });
                }
            }).Wait();
              
            connection.Stop();
    
            Console.ReadLine();
        }
    
        public class HubMes
        {
            public HubMes(string _name,string _mes)
            {
                name = _name;
                message = _mes;
            }
            public string name { get; set; }
            public string message { get; set; }
        }
    }

    chatHub:

    public void Send(string name, string message)
    {
        Clients.All.broadcastMessage(name, $"{message}");
    
        Clients.Others.newMessage(new HubMes(name, message));
    }

    Test Result:

    With Regards,

    Fei Han

    Wednesday, October 10, 2018 3:08 AM