SignalR使用心得...

新手首次使用可使用Nuget下载实例代码:搜索:Microsoft.AspNet.SignalR.Sample

SignalR官方说明:

https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr

SignalR好处显而易见,  就是说哪怕是的项目是.net3.0 开始就使用SignalR,你以后升级成.net4.5了, 你想用websocket你可以直接升级, 因为SignalR会帮你选择你不需要关心。

注意事项:

  • 在SignalR中使用websocket

但是如果需要在SignalR中使用websocket必须满足:

  • 浏览器支持
  • 新的Windows运行时 (win server 12 和win10)
  • IIS 8.0
  • .NET 4.5
    • ASP.NET
    • WCF
    • HttpListener

服务器中安装websocket及注意事项:https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-websocket-protocol-support

装完后需要在webconfig中增加:

<system.web>
    <httpRuntime targetFramework="4.5" />
  </system.web>
  • 在SignalR中使用长轮询


 
如果SignalR服务和应用服务 不在同一个服务器 需要使用JsonP解决跨域问题:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Owin;
using Owin;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;

[assembly: OwinStartup(typeof(***.Startup))]
namespace ***
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {  

            /*如何处理错误:在服务器上显式启用详细的错误消息
            客户端:添加事件的处理程序
            hubConnection.Error += ex => Console.WriteLine("SignalR error: {0}", ex.Message);
            */

            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can 
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // 长轮询跨域 (不使用直接注销)
                    //EnableJSONP = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
        }

    }
}

  

 以下列表显示了SignalR使用哪些步骤来决定要使用的传输。

 

  1. 如果浏览器是Internet Explorer 8或更早版本,则使用长轮询。
  2. 如果配置了JSONP(即,连接启动时jsonp参数设置为true),则使用长轮询。
  3. 如果正在进行跨域连接(即,如果SignalR端点与主机页面不在同一个域中),则如果满足以下条件,则将使用WebSocket:

    • 客户端支持CORS(跨源资源共享)。有关哪些客户端支持CORS的详细信息,请参阅caniuse.com上的CORS
    • 客户端支持WebSocket
    • 服务器支持WebSocket

      如果不符合上述任何一个标准,将使用长轮询。有关跨域连接的更多信息,请参阅如何建立跨域连接

  4. 如果未配置JSONP并且连接不是跨域,则如果客户端和服务器都支持,则将使用WebSocket。
  5. 如果客户端或服务器不支持WebSocket,则可以使用服务器发送事件。
  6. 如果服务器发送事件不可用,则尝试使用永久帧。
  7. 如果Forever Frame失败,则使用Long Polling。
原文地址:https://www.cnblogs.com/xulisha123/p/7359013.html