NEWS

技术文章

ASP.NET的WebSocket in接口

编辑:
起点网络
发布时间:
2018-7-13
点击:
一、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>
 
标签  asp.net开发
相关文章

Copyright@宁波阳程网络科技有限公司. All rights reserved. Powered by 阳程网络       备案号:浙ICP备 16017710号