当前位置:网站首页>Asp.Net Core6 WebSocket 简单案例
Asp.Net Core6 WebSocket 简单案例
2022-06-27 05:13:00 【天马3798】
一、Asp.Net Core6 后端,开启并绑定服务器端WebSocket
1. 启动文件启动绑定
//开启并绑定websocket
app.UseWebSockets();
app.Map("/wstest/one", con => {
con.UseWebSockets();
con.Use(async (ctx, next) => {
//创建监听websocket
WsTest ws = new WsTest();
await ws.DoWork(ctx);
await next.Invoke();
});
});
app.Run();2.封装监听响应
public class WsTest
{
//当前请求实例
WebSocket socket = null;
public async Task DoWork(HttpContext ctx)
{
socket = await ctx.WebSockets.AcceptWebSocketAsync();
//执行监听
await EchoLoop();
}
public 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);
//判断类型读取
if (incoming.MessageType == WebSocketMessageType.Text)
{
//incoming.Count 代表,请求内容字节数量
string userMessage = Encoding.UTF8.GetString(seg.Array, 0, incoming.Count);
//接收客户的字符串
userMessage = "You sent: " + userMessage + " at " +
DateTime.Now.ToLongTimeString();
ArraySegment<byte> segResult = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
await socket.SendAsync(segResult, WebSocketMessageType.Text, true, CancellationToken.None);
}
else
{
}
byte[] backInfo = System.Text.UTF8Encoding.Default.GetBytes("服务端相应内容结束");
var outgoing = new ArraySegment<byte>(backInfo, 0, backInfo.Length);
await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}二、客户端连接并监听相应内容
1.html
<input id="Txt" type="text" name="name" value="" />
<button id="sendBtn">点击发送</button>2.js
//创建监听测试
var url = 'ws://' + location.host + '/wstest/one';
var socket = new WebSocket(url);
//创建监听
socket.onopen = function (e) {
console.info('连接成功');
}
socket.onclose = function (e) {
console.info('连接关闭');
}
socket.onmessage = function (e) {
var data = e.data;
console.info(data);
}
socket.onerror = function (e) {
console.info(e);
}
//按钮事件中发送
document.getElementById('sendBtn').onclick = function () {
var text = document.getElementById('Txt').value;
console.info(text);
//执行发送
socket.send(text);
}查看预览结果:

更多:
ASP.NET Core5.0 SignalR CORS 跨域处理
Asp.Net Core6 WebSocket绑定
ASP.NET Core SignalR.NET 客户端
边栏推荐
猜你喜欢

2022-06-26: what does the following golang code output? A:true; B:false; C: Compilation error. package main import “fmt“ func main() { type

双位置继电器RXMD2-1MRK001984 DC220V

牛客练习赛101-C 推理小丑---位运算+思维

Quick sort (non recursive) and merge sort

Microservice system design -- API gateway service design

【NIPS 2017】PointNet++:度量空间中点集的深层次特征学习

Microservice system design -- unified authentication service design
![[station B up dr_can learning notes] Kalman filter 3](/img/40/d3ec97be2f29b76a6c049c26ff4998.gif)
[station B up dr_can learning notes] Kalman filter 3

Microservice system design -- distributed transaction service design

【FPGA】 基于FPGA分频,倍频设计实现
随机推荐
Zener diode zener diode sod123 package positive and negative distinction
Microservice system design -- service registration, discovery and configuration design
Microservice system design - service fusing and degradation design
MySql最详细的下载教程
Microservice system design -- distributed transaction service design
Execution rules of pytest framework
[station B up dr_can learning notes] Kalman filter 3
快速排序(非遞歸)和歸並排序
What is BFC? What's the usage?
When STM32 turns off PWM output, it is a method to fix IO output at high or low level.
AcWing 第 57 场周赛---BC题挺好
【B站UP DR_CAN学习笔记】Kalman滤波3
Microservice system design -- distributed cache service design
Py2neo basic syntax
007 C语言基础:C运算符
Web3还没实现,Web5乍然惊现!
Redis high availability cluster (sentry, cluster)
DAST black box vulnerability scanner part 6: operation (final)
认知篇----2022高考志愿该如何填报
RTP sending PS stream tool (open source)