【问题标题】:SignalR client in asp.netASP.NET 中的 SignalR 客户端
【发布时间】:2012-10-10 07:36:55
【问题描述】:

我在下面的 asp.net 应用程序中创建了一个服务器集线器

public class Calc : Hub
{
    public void CalculateSomething(int a, int b)
    {
        // start working in a new thread
        var task = Task.Factory.StartNew(() => DoCalculate(a, b));

        // attach a continuation task to notify
        // the client when the work is done
        task.ContinueWith(t =>
        {
            System.Threading.Thread.Sleep(2000);
            Clients.addMessage(t.Result);
            Caller.notifyCalculateResult(t.Result);
            System.Threading.Thread.Sleep(2000);
            Caller.notifyCalculateResult("Completed");
            Clients.addMessage("Completed");
        });
    }

    private int DoCalculate(int p1, int p2)
    {
        // do some slow work on the input,
        // e.g. call webservice or I/O.
        int result = p1 + p2;
        //int result = DoSlowWork(p1, p2);
        return result;
    }
}

现在在另一个 asp.net 应用程序中,我使用 SiganlR 客户端创建了一个客户端。但它不能正常工作。我希望在服务器推送到客户端时从服务器获取数据

using System.Threading.Tasks;
using SignalR;
using SignalR.Client;
using SignalR.Client.Hubs;
namespace WebApplication2
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Connect to the service
            var hubConnection = new HubConnection("http://localhost:3119/");

            // Create a proxy to the chat service
            var chat = hubConnection.CreateProxy("Calc");

            // Print the message when it comes in
            chat.On("addMessage", message =>Print(message));

            // Start the connection
            hubConnection.Start().Wait();

            // Send a message to the server
            chat.Invoke("CalculateSomething", 1, 2).Wait();
        }

        private async void Print(object message)
        {
            Response.Write(message);
        }
    }
}

控制台客户端应用程序工作正常。主要问题在于 asp.net,因为它无法处理来自服务器的回调。

【问题讨论】:

    标签: asp.net signalr async-await signalr-hub signalr.client


    【解决方案1】:

    看来你调用服务器端方法错误,试试这个

    chat.Invoke("CalculateSomething", 1, 2).ContinueWith(task =>
    { 
      Console.WriteLine("Value from server {0}", task.Result);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多