Websocket是html5后的产物,对于asp.net core中也得到了支持,首先在NuGet中添加Microsoft.AspNetCore.WebSockets的引用(现在是1.0.1版本,2017年3月7日发布的)。
首先在Configure中添加中间件
1
2
|
//添加websocket中间件 app.UseWebSockets(); |
接下来就要定义自己处理websocket的中间件了,代码如下:
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
using Microsoft.AspNetCore.Http;
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace Asp.NetCore_WebPage.Middleware
{ /// <summary>
/// websocket中间件,客户端发送的信息显示在控件台上,客户端会定时收到服务端推送的时间
/// </summary>
public class WebSocketNotifyMiddleware
{
/// <summary>
/// 管道代理对象
/// </summary>
private readonly RequestDelegate _next;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
public WebSocketNotifyMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// 中间件调用
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
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< byte >(System.Text.Encoding.UTF8.GetBytes($ "{DateTime.Now}" )), System.Net.WebSockets.WebSocketMessageType.Text, true , CancellationToken.None);
Thread.Sleep(1000);
}
}
return this ._next(context);
}
/// <summary>
/// 接收客户端数据方法,这里可以根据自己的需求切换功能代码
/// </summary>
/// <param name="obj"></param>
void Accept( object obj)
{
var webSocket = obj as WebSocket;
while ( true )
{
var acceptArr = new byte [1024];
var result = webSocket.ReceiveAsync( new ArraySegment< byte >(acceptArr), CancellationToken.None).Result;
var acceptStr = System.Text.Encoding.UTF8.GetString(acceptArr).Trim( char .MinValue);
Console.WriteLine( "收到信息:" + acceptStr);
}
}
}
} |
添加中间件扩展
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
|
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
{ /// <summary>
/// websocket通知中间件扩展
/// </summary>
public static class WebSocketNotifyMiddlewareExtensions
{
/// <summary>
/// 使用websocket通知
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseWebSocketNotify(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<WebSocketNotifyMiddleware>();
}
}
} |
这样,就可以在Startup.cs中的Configure中添加自己创建的中间件了,代码如下:
1
2
3
|
//添加websocket中间件 app.UseWebSockets();
app.UseWebSocketNotify();
|
到此服务端创建完成,接下来看客户端:
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
<div> 当前在数据:<div id= "message" ></div>
<div id= "output" ></div>
<input class= "form-control" type= "text" id= "sendtxt" value= "测试" />
<input type= "button" onclick= "start()" value= "开始" />
<input type= "button" onclick= "send()" value= "发送" />
</div> @section scripts{ <script> var socket;
var uri = "ws://localhost:5000/ws" ;
//初始化连接 function doConnect(open, accept, close, error) {
console.log( "doConnect" )
//创建websocket,并定义事件回调 socket = new WebSocket(uri);
socket.onopen = function (e) { open();};
socket.onclose = function (e) { close(); };
socket.onmessage = function (e) {
accept(e.data);
};
socket.onerror = function (e) { error(e.data); };
} //发送信息 function doSend(message) {
console.log( "doSend" )
socket.send(message);
} //关闭socket function doClose() {
console.log( "doClose" )
socket.close();
} //打开连接回调 function open() {
console.log( "open" )
document.getElementById( "message" ).innerText = "连接打开" ;
}
//接收数据回调
function accept(result) {
console.log( "accept" )
document.getElementById( "output" ).innerText=result;
}
//关闭连接回调
function close() {
console.log( "close" )
document.getElementById( "message" ).innerText= "连接关闭" ;
} //错误回调
function error(result) {
console.log( "error" )
alert( "错误:" +result);
}
//开始方法
function start() {
console.log( "start" )
doConnect(open, accept, close, error);
}
function send()
{
console.log( "send" )
doSend(document.getElementById( "sendtxt" ).value);
}
</script>
} |
这里只是一个基本的例子,可以根据自己的业务来实现不同的功能。
本文转自桂素伟51CTO博客,原文链接:http://blog.51cto.com/axzxs/1909795 ,如需转载请自行联系原作者