SignalR客户端未从服务器接收到消息

时间:2020-11-03 17:38:56

标签: c# asp.net signalr

我正在尝试使用SignalR创建服务器客户端环境。我在互联网上阅读了很多信息,在Stack Overflow上也学到了很多信息,但我完全陷于:(

这是我所做的:

我创建了一个ASP.NET Web应用程序.NET框架(作为ISS网站端口50999发布,充当我的服务器)。 我在数据包管理器控制台的解决方案中添加了Microsoft.AspNet.SignalR,Microsoft.AspNet.SignalR.Core,Microsoft.AspNet.SignalR.JS和Microsoft.AspNet.SignalR.SystemWeb。

我创建了一个Owin启动类:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(TestSignalR.Startup))]

namespace TestSignalR
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();
        }
    }
}

我创建了一个中心,并向所有客户发送了返回消息:

[HubName("mart")]
    public class MartHub : Hub
    {
        public Task SendMessage(string user, string message)
        {
            using (StreamWriter file = new StreamWriter(@"C:\temp\logServer.txt", true))
            {
                file.WriteLine("Test");
            }

            // Clients must have an eventhandler for ReceiveMessage
            return Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }

对于我的客户,我使用接收消息处理程序创建了一个简单的控制台应用程序

static void Main(string[] args)
        {
            var connection = new HubConnection("http://127.0.0.1:50999/");
            var myHub = connection.CreateHubProxy("mart");

            myHub.On<string, string>("ReceiveMessage", (user, message) =>
            {
                Console.WriteLine(user, message);
                Console.Read();
            });

            connection.Start().ContinueWith(task => {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error opening the connection:{0}",
                                      task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Connected");
                }

            }).Wait();

            myHub.Invoke<string>("SendMessage","mart","test").ContinueWith(task => {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error calling send: {0}",
                                      task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine(task.Result);
                }
            });

运行客户端时,服务器上的Sendmessage方法运行良好。测试行放置在我的txt文件中。但是..我没有收到来自服务器的消息。

我还通过服务器上default.aspx页面上的按钮尝试了此操作,但这也不起作用。

protected void Button1_Click(object sender, EventArgs e)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<MartHub>();
            context.Clients.All.Send("ReceiveMessage", "Mart", "Test");
        }

我必须忽略一些笨拙的东西,但我无法弄清楚。 任何帮助都可以申请!

0 个答案:

没有答案