Asp.net core中的websocket

发布时间:2020-10-16 20:14:03 作者:桂素伟
来源:网络 阅读:7667

Websockethtml5后的产物,对于asp.net core中也得到了支持,首先在NuGet中添加Microsoft.AspNetCore.WebSockets的引用(现在是1.0.1版本,201737日发布的)。

首先在Configure中添加中间件

//添加websocket中间件
app.UseWebSockets();

接下来就要定义自己处理websocket的中间件了,代码如下:

using Microsoft.AspNetCore.Http;
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
 
namespace Asp.NetCore_WebPage.Middleware
{
    /// <summary>
    /// websocket中间件,客户端发送的信息显示在控件台上,客户端会定时收到服务端推送的时间
    /// </summary>
    public class WebSocketNotifyMiddleware
    {
        /// <summary>
        /// 管道代理对象
        /// </summary>
        private readonly RequestDelegate _next;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        public WebSocketNotifyMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// <summary>
        /// 中间件调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext context)
        {
            //判断是否为websocket请求
            if (context.WebSockets.IsWebSocketRequest)
            {
                //接收客户端
                var webSocket = context.WebSockets.AcceptWebSocketAsync().Result;
                //启用一个线程处理接收客户端数据
                new Thread(Accept).Start(webSocket);
                while (webSocket.State == WebSocketState.Open)
                {
                    webSocket.SendAsync(new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes($"{DateTime.Now}")), System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
                    Thread.Sleep(1000);
                }
            }
            return this._next(context);
 
        }
        /// <summary>
        /// 接收客户端数据方法,这里可以根据自己的需求切换功能代码
        /// </summary>
        /// <param name="obj"></param>
        void Accept(object obj)
        {
            var webSocket = obj as WebSocket;
            while (true)
            {
                var acceptArr = new byte[1024];
 
                var result = webSocket.ReceiveAsync(new ArraySegment<byte>(acceptArr), CancellationToken.None).Result;
 
                var acceptStr = System.Text.Encoding.UTF8.GetString(acceptArr).Trim(char.MinValue);
                Console.WriteLine("收到信息:" + acceptStr);
            }
 
        }
    }
}

添加中间件扩展

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
 
namespace Asp.NetCore_WebPage.Middleware
{
    /// <summary>
    /// websocket通知中间件扩展
    /// </summary>
    public static class WebSocketNotifyMiddlewareExtensions
    {
        /// <summary>
        /// 使用websocket通知
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseWebSocketNotify(
          this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<WebSocketNotifyMiddleware>();
        }
    }
}

这样,就可以在Startup.cs中的Configure中添加自己创建的中间件了,代码如下:

//添加websocket中间件
 app.UseWebSockets();
 app.UseWebSocketNotify();


到此服务端创建完成,接下来看客户端:

<div>
    当前在数据:<div id="message"></div>
    <div id="output"></div>
    <input class="form-control" type="text" id="sendtxt" value="测试" />
    <input type="button" onclick="start()" value="开始" />
    <input type="button" onclick="send()" value="发送" />
</div>
@section scripts{
<script>
var socket;
     var uri = "ws://localhost:5000/ws";
//初始化连接
function doConnect(open, accept, close, error) {
console.log("doConnect")
//创建websocket,并定义事件回调
    socket = new WebSocket(uri);
    socket.onopen = function (e) { open();};
    socket.onclose = function (e) { close(); };
    socket.onmessage = function (e) {
        accept(e.data);
    };
    socket.onerror = function (e) { error(e.data); };
}
//发送信息
function doSend(message) {
    console.log("doSend")
    socket.send(message);
}
//关闭socket
function doClose() {
    console.log("doClose")
    socket.close();
}        
//打开连接回调
        function open() {
            console.log("open")
            document.getElementById("message").innerText = "连接打开";
        }
        //接收数据回调
        function accept(result) {
            console.log("accept")
            document.getElementById("output").innerText=result;
        }
        //关闭连接回调
        function close() {
            console.log("close")
            document.getElementById("message").innerText="连接关闭";
        }//错误回调
        function error(result) {
            console.log("error")
            alert("错误:"+result);
        }
        //开始方法
        function start() {
            console.log("start")
            doConnect(open, accept, close, error);         
        }
        function send()
        {
            console.log("send")
            doSend(document.getElementById("sendtxt").value); 
        }
    </script>
}


这里只是一个基本的例子,可以根据自己的业务来实现不同的功能。


推荐阅读:
  1. 在ASP.NET Core下使用SignalR技术
  2. ASP.NET Core中有哪些托管方式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

asp net core

上一篇:React | 高效前端之浅谈

下一篇:PYTHON发送邮件YAGMAIL的简单实现解析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》