欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.NetCore WebSocket

程序员文章站 2023-12-28 14:47:04
...

我喜欢.NET CORE 这个东西,其实不仅仅源于它性能很高,可以跨平台,还因为它的设计模式确实令人着迷。以前没.NET CORE 的时候,.NET用websocket必须跑在windows server 2012上,但我一般不会这么干,都把websocket架在nodejs的服务器上。这么分出来,麻烦肯定是麻烦的,而且js这东西,写复杂和几年后再看都是头疼的问题。那么,如果.NET CORE是以kestrel运行的,那么就不再需要考虑服务器的版本运行,任何一个地方都可以用websocket


.net core使用websocket非常简单,中间件这个概念在.net core中是体现的淋漓尽致,而且不得不说真的是非常高明的一种设计模式。默认是不启用websocket的,那么我仅仅需要在Configure中app.UseWebSockets();来启用,再自己写一个中间件即可

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Builder;

namespace Common
{
    public static class MidWare
    {
        public static IApplicationBuilder UseWebSocket(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<SocketHelper.WebSocketMidWare>();
        }
    }
}



Configure中app.UseWebSocket();



using System;
using System.Collections.Generic;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Chloe.Model;
using Microsoft.AspNetCore.Http;
using Model;

namespace Common
{
    public class SocketHelper
    {
        public static async Task<string> RecvAsync(WebSocket webSocket, CancellationToken cancellationToken)
        {
            var ms = new MemoryStream();
            var buffer = new ArraySegment<byte>(new byte[1024 * 8]);

            WebSocketReceiveResult result;
            do
            {
                result = await webSocket.ReceiveAsync(buffer, cancellationToken);
                ms.Write(buffer.Array, buffer.Offset, result.Count - buffer.Offset);
            } while (!result.EndOfMessage);
            ms.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(ms);
            var s = reader.ReadToEnd();
            reader.Dispose();
            ms.Dispose();
            return s;
        }


        public static async Task SendAsync(WebSocket webSocket,string msg )
        {
            CancellationToken cancellation=default(CancellationToken);
            var buf = Encoding.UTF8.GetBytes(msg);
            var segment = new ArraySegment<byte>(buf);
            await webSocket.SendAsync(segment, WebSocketMessageType.Text, true, cancellation);
        }
        public class WebSocketMidWare
        {
            private readonly RequestDelegate _next;
            public WebSocketMidWare(RequestDelegate next)
            {
                _next = next;
            }

            public async Task Invoke(HttpContext context)
            {
                if (context.Request.Path == "/ws" && context.WebSockets.IsWebSocketRequest)
                {
                    var socket = await context.WebSockets.AcceptWebSocketAsync();
                }
                else
                {
                    await _next(context);
                }
            }
        }

    }
}


相关标签: C# .NetCore

上一篇:

下一篇: