当前位置:网站首页>Build websocket server in. Net5 webapi
Build websocket server in. Net5 webapi
2022-04-23 03:18:00 【Pingshan CP3】
background : We need to develop a WebSocket Server side , Used to direct to h5 Client push message ; The previous practice was to directly make a windows service , Open a special port for WebSocket Connect , Now you can .net5 WebAPI Directly support WebSocket, And there is no need to open a single port
Use steps :
1. stay Startup.cs Of Configure Enable WebSocket middleware
app.UseWebSockets();
2. Add... To the controller Action, To receive WebSocket The connection and processing of the client receive 、 Send a message , Close the connection ;
[HttpGet("/ws")]
public async Task Get()
{
if (HttpContext.WebSockets.IsWebSocketRequest)
{
// Accept websocket Client connection
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
await Echo(webSocket);
}
else
{
// No websocket Client request
HttpContext.Response.StatusCode = 400;//
}
}
/// <summary>
/// Processing of clients , Receive a message , Send a message , Close the connection
/// </summary>
/// <param name="webSocket"></param>
/// <returns></returns>
private async Task Echo(WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
var serverMsg = Encoding.UTF8.GetBytes($"Server: Hello. You said: {Encoding.UTF8.GetString(buffer)}");
// Send a message to the client
await webSocket.SendAsync(new ArraySegment<byte>(serverMsg, 0, serverMsg.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
// Continue to accept client messages
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
// Close and release the connection with the client
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
3. You can do it according to your own business , For example, store a client dictionary to maintain , Specify the client to send messages .
4.H5 That's how it works :
let ws = new WebSocket('ws://api.zhandian.com/ws');// The connection is api Address of the website
ws.onmessage = function (e) {
// Listen to the message
console.log(e);
console.log(e.data);
};
Of course I am now websocket Not many clients , If you don't know how many clients there are , Will this affect api Interface , Waiting for verification
版权声明
本文为[Pingshan CP3]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220627117044.html
边栏推荐
- [mock data] fastmock dynamically returns the mock content according to the incoming parameters
- First in the binary tree
- [MySQL] left Function | Right Function
- Improvement of ref and struct in C 11
- Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types
- JS inheritance
- 2022t elevator repair test simulation 100 questions and online simulation test
- Explication détaillée des fonctions send () et recv () du programme Socket
- 2022年做跨境电商五大技巧小分享
- js 中,为一个里面带有input 的label 绑定事件后在父元素绑定单机事件,事件执行两次,求解
猜你喜欢
After the mobile phone is connected to the computer, how can QT's QDIR read the mobile phone file path
Idea view history [file history and project history]
“如何实现集中管理、灵活高效的CI/CD”在线研讨会精彩内容分享
Web Course Design - his system
Explanation keyword of MySQL
《C语言程序设计》(谭浩强第五版) 第8章 善于利用指针 习题解析与答案
ASP. Net 6 middleware series - execution sequence
2022年度Top9的任务管理系统
2022 Shandong Province safety officer C certificate work certificate question bank and online simulation examination
Blazor University (12) - component lifecycle
随机推荐
研讨会回放视频:如何提升Jenkins能力,使其成为真正的DevOps平台
2022年度Top9的任务管理系统
关于idea调试模式下启动特别慢的优化
Cefsharp stores cookies and reads cookies
C语言实现通讯录----(静态版本)
MySql分组查询规则
数据库表中不建索引,在插入数据时,通过sql语句防止重复添加(转载)
[untitled]
OLED多级菜单记录
Ide-idea-problem
Chapter 8 of C language programming (fifth edition of Tan Haoqiang) is good at using pointer exercises to analyze and answer
[MySQL] left Function | Right Function
. net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
Seminar playback video: how to improve Jenkins' ability to become a real Devops platform
月薪10k-20k都无法回答的事务问题,你会吗?
be based on. NETCORE development blog project starblog - (2) environment preparation and creation project
Queue storage and circular queue
2022年P气瓶充装培训试题及模拟考试
Super easy to use asynchronous export function of Excel
Why is bi so important to enterprises?