Asp.netcore中的websocket
Websocket是html5后的产物,对于asp.net core中也得到了支持,首先在NuGet中添加Microsoft.AspNetCore.WebSockets的引用(现在是1.0.1版本,2017年3月7日发布的)。

创新互联公司2013年开创至今,先为凤县等服务建站,凤县等地企业,进行企业商务咨询服务。为凤县企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
首先在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
{
///
/// websocket中间件,客户端发送的信息显示在控件台上,客户端会定时收到服务端推送的时间
///
public class WebSocketNotifyMiddleware
{
///
/// 管道代理对象
///
private readonly RequestDelegate _next;
///
///
///
///
public WebSocketNotifyMiddleware(RequestDelegate next)
{
_next = next;
}
///
/// 中间件调用
///
///
///
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(System.Text.Encoding.UTF8.GetBytes($"{DateTime.Now}")), System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
Thread.Sleep(1000);
}
}
return this._next(context);
}
///
/// 接收客户端数据方法,这里可以根据自己的需求切换功能代码
///
///
void Accept(object obj)
{
var webSocket = obj as WebSocket;
while (true)
{
var acceptArr = new byte[1024];
var result = webSocket.ReceiveAsync(new ArraySegment(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
{
///
/// websocket通知中间件扩展
///
public static class WebSocketNotifyMiddlewareExtensions
{
///
/// 使用websocket通知
///
///
///
public static IApplicationBuilder UseWebSocketNotify(
this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
} 这样,就可以在Startup.cs中的Configure中添加自己创建的中间件了,代码如下:
//添加websocket中间件 app.UseWebSockets(); app.UseWebSocketNotify();
到此服务端创建完成,接下来看客户端:
当前在数据:@section scripts{ }
这里只是一个基本的例子,可以根据自己的业务来实现不同的功能。
文章标题:Asp.netcore中的websocket
本文路径:http://www.jxjierui.cn/article/joejjp.html


咨询
建站咨询
