服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - ASP.NET教程 - Asp.Net Core中WebSocket绑定的方法详解

Asp.Net Core中WebSocket绑定的方法详解

2020-05-21 14:22天马3798 ASP.NET教程

WebSocket 是一种在单个 TCP 连接上进行全双工通讯的协议,是建立在TCP上、且独立的协议。下面这篇文章主要给大家介绍了关于Asp.Net Core中WebSocket绑定的方法,需要的朋友可以参考借鉴,下面来一起看看吧。

说明

Websocket是html5后的产物,对于asp.net core中也得到了支持,Asp.Net Core中WebScoket的操作使用基本上和Asp.net中相同,不同的是,绑定监听。

Asp.Net Core2.0默认已经支持WebSocket,不需要另外安装Nuget包。

通过对HttpContext中的WebSockets.AcceptWebSocketAsync方法,接受WebSocket请求;并返回WebScoket对象。

下面话不多说了,来一起看看详细的介绍吧。

一、示例1,

1.后台启动文件Startup的configure中绑定WebSocket的路由监听

?
1
2
3
4
5
6
7
8
9
10
11
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp)
{
......
 //绑定WebSocket
 app.Map("/wsone/Connect", (con) =>
 {
  con.UseWebSockets();
  WSHanleTwo _two = new WSHanleTwo();
  con.Use(_two.Connect);
 });
}

2.定义请求处理类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace Core_Razor_2
{
 public class WSHanleTwo
 {
  private WebSocket socket = null;
  //创建链接
  public async Task Connect(HttpContext context, Func<Task> n)
  {
   try
   {
    //执行接收
    WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();
    this.socket = socket;
    //执行监听
    await EchoLoop();
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }
  /// <summary>
  /// 响应处理
  /// </summary>
  /// <returns></returns>
  async Task EchoLoop()
  {
   var buffer = new byte[1024];
   var seg = new ArraySegment<byte>(buffer);
   while (this.socket.State == WebSocketState.Open)
   {
    var incoming = await this.socket.ReceiveAsync(seg, CancellationToken.None);
    byte[] backInfo = System.Text.UTF8Encoding.Default.GetBytes("服务端相应内容");
    var outgoing = new ArraySegment<byte>(backInfo, 0, incoming.Count);
    await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
   }
  }
 }
}

3.前台请求代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var socket;
//var uri = "ws://" + window.location.host + "/ws";
var uri = "ws://" + window.location.host + "@Url.Action("Connect")";
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;

二、为了简单绑定,可以这样封装

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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>
 /// 路由绑定处理
 /// </summary>
 /// <param name="app"></param>
 public static void Map(IApplicationBuilder app)
 {
  app.UseWebSockets();
  app.Use(SocketHandler.Acceptor);
 }
}

路由绑定:

?
1
2
3
[csharp] view plain copy
//绑定websocket
app.Map("/ws", SocketHandler.Map);

Asp.Net Core上传控件:Uploader.rar

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://blog.csdn.net/u011127019/article/details/77408072

延伸 · 阅读

精彩推荐