简体   繁体   中英

How to get something from server using SignalR

I need to create method, which can request to server and return answer. But if I use SignalR, I can run server's method and server will run client's method. But how I can create something like this template?

public Response Request()
{
    //???
}

if I use SignalR, I can run server's method and server will run client's method.

If you'd like to invoke hub method from .NET client application in c#, you can refer to the following code snippet.

try
{
    HubConnection connection = new HubConnectionBuilder()
    .WithUrl("http://localhost:61262/chatHub")
    .Build();

    await connection.StartAsync();

    var mes = "hello";

    await connection.InvokeAsync("SendMessage", "Consloe Client", mes);

    // await connection.StopAsync();
}
catch (Exception ex)
{

    Console.WriteLine("Can not communicate with server now, please retry later.");
}

Hub method

public async Task SendMessage(string user, string message)
{          
    await Clients.All.SendAsync("ReceiveMessage", user, message);
}

Besides, to setup Hub and client, please refer to the following articles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM