WebSocket in ASP.NET Core

一、WebSocket

  WebSocket是HTML5出的东西(协议),也就是说HTTP协议没有变化,或者说没关系,但HTTP是不支持持久连接的(长连接,循环连接的不算)

首先HTTP有1.1和1.0之说,也就是所谓的keep-alive,把多个HTTP请求合并为一个,但是Websocket其实是一个新协议,跟HTTP协议基本没有关系,只是为了兼容现有浏览器的握手规范而已,也就是说它是HTTP协议上的一种补充。WS和WSS协议类似于HTTP和HTTPS,允许使用安全和保密的通信方案。

二、ASP.NET Core中的WebSocket

  要在ASP.NET Core中使用WebSocket,要先引用Microsoft.AspNetCore.WebSockets.Server的NuGet Package包。

  下面我们创建一个名为WebSocketHandler.cs的类,内容如下:

  通过对HttpContext中的WebSockets.AcceptWebSocketAsync方法,接受WebSocket请求;并在EchoLoop函数中进行请求的处理。

 public class SocketHandler
    {
        public const int BufferSize = 4096;

        WebSocket socket;

        SocketHandler(WebSocket socket)
        {
            this.socket = socket;
        }

        async Task EchoLoop()
        {
            var buffer = new byte[BufferSize];
            var seg = new ArraySegment<byte>(buffer);

            while (this.socket.State == WebSocketState.Open)
            {
                var incoming = await this.socket.ReceiveAsync(seg, CancellationToken.None);
                var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count);
                await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }

        static async Task Acceptor(HttpContext hc, Func<Task> n)
        {
            if (!hc.WebSockets.IsWebSocketRequest)
                return;

            var socket = await hc.WebSockets.AcceptWebSocketAsync();
            var h = new SocketHandler(socket);
            await h.EchoLoop();
        }

        /// <summary>
        /// branches the request pipeline for this SocketHandler usage
        /// </summary>
        /// <param name="app"></param>
        public static void Map(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.Use(SocketHandler.Acceptor);
        }
    }

  这个类只处理了最简单的客户端发送信息并将原文返回客户端。

  接着就要做路由映射了:

  app.UseStaticFiles();
  app.Map("/ws", SocketHandler.Map);

  要验证并看到运行的结果,我们还要创建一个Html。并在Html页面里面创建一个Div内容如下:

<div id="output"></div>

  并且添加一个WebSocket的客户端脚本:

 

<script language="javascript" type="text/javascript">
var socket;
var uri = "ws://" + window.location.host + "/ws";
var output;
var text = "test echo";

function write(s) {
    var p = document.createElement("p");
    p.innerHTML = s;
    output.appendChild(p);
}

function doConnect() {
    socket = new WebSocket(uri);
    socket.onopen = function (e) { write("opened " + uri); doSend(); };
    socket.onclose = function (e) { write("closed"); };
    socket.onmessage = function (e) { write("Received: " + e.data); socket.close(); };
    socket.onerror = function (e) { write("Error: " + e.data); };
}

function doSend() {
    write("Sending: " + text);
    socket.send(text);
}

function onInit() {
    output = document.getElementById("output");
    doConnect();
}

window.onload = onInit;

</script>

 

  下面就可以看到运行结果了:

 

 

  这个例子可以在如下Github中获取到:https://github.com/zbrad/wsweb

 .NET Core 开源学习群: 214741894   

 

posted @ 2016-12-21 16:30  YOYOFx  阅读(7481)  评论(10编辑  收藏  举报