SignalR的Javascript客户端API使用方式整合

时间:2023-12-05 08:09:14
  PersistentConnection Hub/生成Proxy模式 Hub/非生成Proxy模式
服务端配置

app.Map("/messageConnection", map =>
           {
               map.RunSignalR<MessageConnection>();
           });

app.Map("/messageHub", map =>
           {
               map.RunSignalR(new Microsoft.AspNet.SignalR.HubConfiguration { EnableJavaScriptProxies = true });
           });

app.Map("/messageHub", map =>
            {
                map.RunSignalR(new Microsoft.AspNet.SignalR.HubConfiguration { EnableJavaScriptProxies = true });
            });

引入js文件 jquery-1.6.4.min.js
jquery.signalR-2.2.0.min.js
jquery-1.6.4.min.js
jquery.signalR-2.2.0.min.js
/messageHub/js
上述js文件是动态生成,其中messageHub的为服务端定义的路径
jquery-1.6.4.min.js
jquery.signalR-2.2.0.min.js
创建连接 var connection = $.connection("/message"); var connection = $.connection; var connection = $.hubConnection();
开启连接

connection.start()
                .done(function () {
                    connected = true;
                })
                .fail(function () {
                    alert("连接失败");
                });

connection.hub.start()
                .done(function () {
                    connected = true;
                })
                .fail(function () {
                    alert("连接失败");
                });

connection.start()
                .done(function () {
                    connected = true;
                })
                .fail(function () {
                    alert("连接失败");
                });

代理对象 var proxy = connection.MessageService;
MessageService是Hub的名称
var proxy = connection.createHubProxy("MessageService");
MessageService是Hub的名称
定义客户端方法

proxy.client.hello = function (message) {
                      console.log(message);

}

proxy.on("hello", function (message) {

console.log(message);

});

接收消息

connection.received(function (message) {
                alert(message);
            });

通过服务器调用客户端方法实现

通过服务器调用客户端方法实现

发送消息 connection.send(message); 通过调用服务端方法实现
proxy.server.hello(message);
通过调用服务端方法实现
proxy.invoke("hello", message);
设置QueryString 在创建connection时指定
var connection = $.connection("/messageConnection", { username: "qs" + username });
connection.hub.qs = { username: "qs" + username }; connection.qs = { username: "qs" + username };
设置Cookie document.cookie = "username=" + username; document.cookie = "username=" + username; document.cookie = "username=" + username;
设置State proxy.state.ClientType = "HubAutoProxy"; proxy.state.ClientType = "HubNonAutoProxy";