.NET-Core Series

Introduce

  上篇博文中,介绍了WebSocket 的基本原理,以及一个简单的Demo用来对其有一个大致的认识。这篇博文讲的是我们平常在网站上可能会经常遇到的——实时聊天,本文就是来讲在.NET-Core 使用WebSocket来实现一个“乞丐版”的在线实时聊天Demo。

关键词Middleware,Real-Time,WebSocket

Before You Read.

 这个和我们上一篇博文中Demo 有何不同的呢?有何共同之处呢?

 相同的点是,都是网页作为客户端,使用JavaScript 来发送和接收请求,.NET-Core 服务端接收到请求,发送该请求给客户端。

不同的地方呢,就像我下面这张图这样:

一次同时有多个客户端在,所以应该很清楚,我们只要在上面例子的基础上,对当前的已存在的Socket进行轮询,发送回应即可达到我们想要的效果。

Create WebSocket Middleware

 在上个Demo的例子中,我们直接在StartupConfigure 中直接写接受WebSocket请求。这次我们换成Middleware形式来处理。在写Middleware之前,在之前的介绍中,我们知道,需要有多个WebSocket,那么肯定需要一些对WebSocketGet/Set 处理。我简单的写了一个下面WebScoket Manger Class

//WebSocketManager.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace WebSocketManage
{
public class WSConnectionManager
{
private static ConcurrentDictionary<string, WebSocket> _socketConcurrentDictionary = new ConcurrentDictionary<string, WebSocket>(); public void AddSocket(WebSocket socket)
{
_socketConcurrentDictionary.TryAdd(CreateGuid(), socket);
} public async Task RemoveSocket(WebSocket socket)
{
_socketConcurrentDictionary.TryRemove(GetSocketId(socket), out WebSocket aSocket); await aSocket.CloseAsync(
closeStatus: WebSocketCloseStatus.NormalClosure,
statusDescription: "Close by User",
cancellationToken: CancellationToken.None).ConfigureAwait(false);
} public string GetSocketId(WebSocket socket)
{
return _socketConcurrentDictionary.FirstOrDefault(k => k.Value == socket).Key;
} public ConcurrentDictionary<string, WebSocket> GetAll()
{
return _socketConcurrentDictionary;
} public string CreateGuid()
{
return Guid.NewGuid().ToString();
}
}
}

上面主要是对 WebSocket 进行了简单的存取操作进行了封装。下面也把WebSocketSendRecieve 操作进行了封装。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace WebSocketManage
{
public class WSHandler
{
protected WSConnectionManager _wsConnectionManager; public WSHandler(WSConnectionManager wSConnectionManager)
{
_wsConnectionManager = wSConnectionManager;
} public async Task SendMessageAsync(
WebSocket socket,
string message,
CancellationToken cancellationToken = default(CancellationToken))
{
var buffer = Encoding.UTF8.GetBytes(message);
var segment = new ArraySegment<byte>(buffer); await socket.SendAsync(segment, WebSocketMessageType.Text, true, cancellationToken);
}
public async Task<string> RecieveAsync(WebSocket webSocket, CancellationToken cancellationToken)
{
var buffer = new ArraySegment<byte>(new byte[1024 * 8]);
using (var ms = new MemoryStream())
{
WebSocketReceiveResult result;
do
{
cancellationToken.ThrowIfCancellationRequested(); result = await webSocket.ReceiveAsync(buffer, cancellationToken);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage); ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType != WebSocketMessageType.Text)
{
return null;
} using (var reader = new StreamReader(ms, Encoding.UTF8))
{
return await reader.ReadToEndAsync();
}
}
}
}
}

有了上面两个辅助类之后,接下来就可以写我们自己的RealTimeWebSocketMiddlerware 了,

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocketManage; namespace Robert.Middleware.WebSockets
{
public class RealTimeWSMiddleware
{
private readonly RequestDelegate _next;
private WSConnectionManager _wSConnectionManager { get; set; }
private WSHandler _wsHanlder { get; set; } public RealTimeWSMiddleware(
RequestDelegate next,
WSConnectionManager wSConnectionManager,
WSHandler wsHandler)
{
_next = next;
_wSConnectionManager = wSConnectionManager;
_wsHanlder = wsHandler;
} public async Task Invoke(HttpContext httpContext)
{
if (httpContext.WebSockets.IsWebSocketRequest)
{
var cancellationToken = httpContext.RequestAborted;
var currentWebSocket = await httpContext.WebSockets.AcceptWebSocketAsync();
_wSConnectionManager.AddSocket(currentWebSocket); while (true)
{
if (cancellationToken.IsCancellationRequested) break;
var response = await _wsHanlder.ReceiveAsync(currentWebSocket, cancellationToken); if (string.IsNullOrEmpty(response) && currentWebSocket.State != WebSocketState.Open) break; foreach (var item in _wSConnectionManager.GetAll())
{
if (item.Value.State == WebSocketState.Open)
{
await _wsHanlder.SendMessageAsync(item.Value, response, cancellationToken);
}
continue;
}
} await _wSConnectionManager.RemoveSocket(currentWebSocket);
}
else
{
await _next(httpContext);
}
}
}
}

 其实到这里,核心部分已经讲完了,接下来就是页面显示,发现信息,交互的问题了。在客户端还是像上篇文章中的一样,直接使用 JavaScript 发送WebScoket请求。

 下面主要演示一下效果,在上篇博文的基础上,加上了用户名。

<script>
$(function () {
var protocol = location.protocol === "https:" ? "wss:" : "ws:";
var Uri = protocol + "//" + window.location.host + "/ws";
var socket = new WebSocket(Uri);
socket.onopen = e => {
console.log("socket opened", e);
}; socket.onclose = function (e) {
console.log("socket closed", e);
}; //function to receive from server.
socket.onmessage = function (e) {
console.log("Message:" + e.data);
$('#msgs').append(e.data + '<br />');
}; socket.onerror = function (e) {
console.error(e.data);
};
});
</script>

当写好了页面文件后,运行站点。最终运行的效果图,界面以实用为主,不求美观。

WebSocket In ASP.NET Core(二)的更多相关文章

  1. WebSocket in ASP.NET Core

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

  2. WebSocket In ASP.NET Core(一)

    .NET-Core Series Server in ASP.NET-Core DI in ASP.NET-Core Routing in ASP.NET-Core Error Handling in ...

  3. K8S+GitLab-自动化分布式部署ASP.NET Core(二) ASP.NET Core DevOps

    一.介绍 前一篇,写的K8S部署环境的文章,简单的介绍下DevOps(Development和Operations的组合词),高效交付, 自动化流程,来减少软件开发人员和运维人员的沟通.Martin ...

  4. asp.net core 二 Nginx Supervisor 负载,监听

           ASP.NET Core负载均衡集群搭建(CentOS7+Nginx+Supervisor+Kestrel)          asp.net core在linux运行下,一但命令行退出 ...

  5. ASP.NET Core (二):入门

    上一篇:ASP.NET Core(一):简介 下一篇:(待续) 英文原版:Getting Started 1. 安装 .NET Core 2. 创建 .NET Core 项目 在命令提示符窗口输入命令 ...

  6. asp.net core系列 70 即时通迅-WebSocket+Redis发布订阅

    一.概述 在asp.net core 中可以用WebSocket 或asp.net core SignalR来开发即时通迅.在项目中由于开发前后端分离,对于SignalR前端技术人员不想依赖juqer ...

  7. 使用websocket连接(对接)asp.net core signalr

    使用通用websocket连接asp.net core signalr 一.背景介绍 signalr的功能很强大,可以为我们实现websocket服务端节省不少的时间.但是可能由于不同的环境,我们在对 ...

  8. 在ASP.NET Core下使用SignalR技术

    一.前言 上次我们讲到过如何在ASP.NET Core中使用WebSocket,没有阅读过的朋友请参考 WebSocket in ASP.NET Core 文章 .这次的主角是SignalR它为我们提 ...

  9. ASP.NET Core (一):简介

    下一篇:ASP.NET Core(二):入门 英文原版:Introduction to ASP.NET Core 关于ASP.NET Core ASP.NET Core 是一个全新的开源.跨平台框架, ...

随机推荐

  1. 没有基础如何学习web渗透测试?

    如果只是因为感兴趣玩玩的话,你可以不需要学习太多的脚本程序. 但是以下条件要具备 1.能看懂教程:能理解原理,例如解析漏洞,sql注入逻辑等 2.前端代码审计:html js css 3.主流工具的使 ...

  2. 使用Groovy处理SoapUI中Json response

    最近工作中,处理最多的就是xml和json类型response,在SoapUI中request里面直接添加assertion处理json response的话,可以采用以下方式: import gro ...

  3. 怎样通过js 取消input域的hidden属性使其变的可见

    document.getElementById(ID).setAttribute("hidden",false);厉害了 我的哥!

  4. Flask01 路由控制(转换器)、反转、请求方法控制

    1 提出问题 如何实现前端传过去的路径时动态的(即:多个url对应一个url视图函数) 例如: 浏览器中输入 http://127.0.0.1:5000/test/good/ 或者 http://12 ...

  5. WCF(一)基础整理

    学习WCF之前,了解下WCF和WebService的区别. WCF和WebService区别 Web Service严格来说是行业标准,也就是Web Service 规范,它使用XML扩展标记语言来表 ...

  6. (一)Builder(建造者)模式

    我们一般在构建javabean的对象的时候通常有三种写法: 1.直接通过构造函数传参的方式设置属性,这种方法如果属性过多的话会让构造函数十分臃肿,而且不能灵活的选择只设置某些参数. 2.采用重叠构造区 ...

  7. 入门-什么是webshell?

    webshell是什么? 顾名思义,"web" - 显然需要服务器开放web服务,"shell" - 取得对服务器某种程度上操作权限. webshell常常被称 ...

  8. windows 下 Mutex和Critical Section 区别和使用

    Mutex和Critical Section都是主要用于限制多线程(Multithread)对全局或共享的变量.对象或内存空间的访问.下面是其主要的异同点(不同的地方用黑色表示). Mutex Cri ...

  9. JAVA基础第六组(5道题)

    26.[程序26] 题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续 判断第二个字母.         1.程序分析:用情况语句比较好,如果第一个字母一样,则判断用情况语句 ...

  10. bean的单例

    通过改变中的scope属性,默认是singleton单例.而prototype则指定每getbean得到的都是不同实例. 验证代码: ①:验证默认singleton //验证<bean id=& ...