调用SignalR中的服务器和客户端方法

Calling server and client method in SignalR

本文关键字:客户端 方法 服务器 SignalR 调用      更新时间:2024-05-24

以下代码采用ASP.Net SignalR Hub技术。这些代码未按预期工作。当我点击Hello Butting时,它运行良好,但当我点击UserList时,什么都没有发生。我已经发出警报,发现服务器方法正在调用,但之后什么也没发生。

JavaScript

$(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;
    chat.client.OnlineFriends = function (userLists) {
        alert(userLists);
    };
    chat.client.Hello = function (message) {
        alert(message);
    };
    // Start the connection.
    $.connection.hub.start().done(function () {
        $('#btnGetUser').click(function () {
            chat.server.Friends();
        });
        $('#btnHello').click(function () {                    
            chat.server.test("message to server from client");                    
            //
        });
    });
});

和C#代码

public class ChatHub : Hub
{
    public void Test(string str)
    {
        Clients.Caller.Hello(str + " | Message received at server reply from server.");
    }
    public void Friends()
    {
        Clients.Caller.OnlineFriends("myid");
    }
}

和HTML

<div>
    <input type="button" id="btnHello" value="Hello" />
    <input type="button" id="btnGetUser" value="UserList" />
</div>

请帮忙找出问题出在哪里。

你能试着更改行吗

chat.server.Friends();

至:

chat.server.friends();

我猜生成的javascript具有关于命名的java约定。这是我能从这两种方法中看到的唯一区别。

正如@scheien所提到的,您需要使用小写首字母来调用该方法。或者,您可以指定集线器方法名称,如这里详细介绍的那样。

[HubMethodName("MyNewMethodName")]
public void Friends()

然后使用新名称调用服务器功能

chat.server.MyNewMethodName();
chat.client.onlineFriends = function (userLists) {
        alert(userLists);
    };

但是。。。。。。集线器上不存在userLists

Clients.CalleronlineFriends("myid");

这是一回事,另一件让我头疼的事是javascript部分没有以大写字母开头

因此,您还必须将FriendsHelloOnlineFriends更改为friendshelloonlineFriends