65.9K
CodeProject 正在变化。 阅读更多。
Home

SignalR Hello World(这不是一个聊天应用)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.80/5 (4投票s)

2015年1月17日

CPOL

3分钟阅读

viewsIcon

19243

SignalR Hello World(这不是一个聊天应用)

我一直想尝试一下 SignalR,终于想到了一个足够简单的入门方案(不是聊天应用程序)。

我不会深入探讨 SignalR 的工作原理,只是向你展示入门代码。如果你从未听说过 SignalR,请阅读这里的前两段。

我们的应用将执行以下操作:

  • 用户在他们的桌面电脑上导航到一个页面。我们将在页面上显示一个二维码。
  • 用户将使用他们的智能手机扫描二维码,并被重定向到他们手机浏览器上的一个页面。
  • 用户将在他们的桌面电脑上看到他们手机的实时方向数据。

为了保持文章简短,我只会展示与 SignalR 相关的代码。你可以查看演示源代码以获取完整细节。

开始吧

打开 Visual Studio 并创建一个新的ASP.NET MVC 5应用程序。

通过 NuGet 获取以下库:

  • Microsoft ASP.NET Web SignalR

在服务器端

我们需要做的第一件事是将 SignalR 挂接到我们的应用程序启动。我们通过创建一个文件并添加以下代码来执行此操作。当应用程序启动时,Configuration 函数将自动被调用。*注意:SneakySignal 是项目的名称,与 SignalR 无关。

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SneakySignal.Startup))]
namespace SneakySignal
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

接下来,我们需要添加处理服务器和客户端之间通信的代码。现在,你只需要知道 SignalR 使用 Hub 的概念。你可以在这里了解更多信息。

创建继承自 HubMotionHub.cs类。

using Microsoft.AspNet.SignalR;
namespace SneakySignal
{
    public class MotionHub : Hub
    {
        //Desktop and phone uses this to get their connection id
        public string GetConnectionId()
        {
            return Context.ConnectionId;
        }

        //Called by the phone
        //Tells the desktop that the phone wants to connect
        public void ClientConnected(string connectionId)
        {
            var clientId = Context.ConnectionId;
            Clients.Client(connectionId).clientConnected(clientId);
        }

        //Called by the desktop
        //Tells the phone that it is connected and can start sending data
        public void StartExecution(string connectionId)
        {
            Clients.Client(connectionId).startExecution();
        }

        //Called by the phone
        //Tells the desktop that the orientation has changed
        public void OrientationChanged(string connectionId, OrientationData orientationData)
        {
            Clients.Client(connectionId).orientationChanged(orientationData);
        }
    }

    public class OrientationData
    {
        public decimal Alpha { get; set; }
        public decimal Beta { get; set; }
        public decimal Gamma { get; set; }
    }
}

正如你所看到的,我们只需要编写特定于我们应用程序的业务逻辑,因为 SignalR 会处理所有连接管理。

最后,在你的_layout.cshtml文件中添加以下行:

/Scripts/jquery.signalR-2.1.2.min.js
/signalr/js

/signalr/js 是 SignalR 使用的约定。在构建时,我们的 MobileHub 将生成一些 JavaScript,这些 JavaScript 将在这个路由上找到。

现在是客户端实现的部分。

桌面客户端

var hub = $.connection.motionHub;
//register mobile and tell it to start executing
hub.client.ClientConnected = function (clientId) {
    hub.server.startExecution(clientConnectionId);
};
//update orientation
hub.client.orientationChanged = function (orientation) {

};

//connect to server
$.connection.hub.start().done(function () {
    hub.server.getConnectionId().done(function (desktopConnectionId) {
        //show QR code with url containing desktop connection id
    });
})

你首先会看到,我们从 $.connection.motionHub 获取我们的特定 Hub。然后,我们订阅在我们的MotionHub.cs文件中指定的 clientConnectedorientationChanged 方法。

最后,使用 $.connection.hub.start() 连接到服务器。当我们连接到服务器时,我们要求它提供我们的连接 ID。

移动客户端

var hub = $.connection.motionHub;

hub.client.StartExecution = function () {
  window.addEventListener("deviceorientation", function(orientation){
        hub.server.orientationChanged(desktopConnectionId, orientation);
  });
};
//connect to server
$.connection.hub.start().done(function () {
    hub.server.clientConnected(desktopConnectionId).done();
});

移动端的 JavaScript 非常相似。首先,我们订阅 startExecution。在这个方法中,我们添加一个事件监听器,监听 deviceorientation 事件。在事件发生时,我们使用新的方向调用服务器上的 orientationChanged

剩下的就是连接到服务器,并告诉相关的桌面客户端我们想要连接到它。

*注意。为了保持简洁,我省略了很多逻辑,例如事件节流等。

为了总结实际发生的事情,请查看下面的图片:


就这样

我对能够如此轻松地完成一些很棒的事情感到印象深刻。显然,SignalR 还有更多功能,你可以用它来做很多事情,但对于一个 Hello World 来说,这个结果真的很棒。跳到演示看看吧。


这篇文章最初发表在 blog.entelect.co.za

© . All rights reserved.