.net 5 使用WebSocket

前台简单构造:

window.location.search.replace("?","") 获取页面传值zs或者ls
复制代码
<html>
<head>
    <script type="text/javascript">
           const webSochet= new WebSocket('ws://localhost:47471/ws');

           var origin=window.location.search.replace("?","");

           webSochet.onopen=function(res)
           {
               webSochet.send(origin);
           }

           webSochet.onmessage=function(res)
           {
               console.log(res.data);
           }

           function add(){
               var msg=document.getElementById("msg").value;
               var to=document.getElementById("to").value;
               webSochet.send(`${msg}***${to}`);
           }
    </script>
</head>
<body>
    <textarea id="msg">

    </textarea>
    发给:<select id="to">
            <option>请选择</option>
            <option>zs</option>
            <option>ls</option>
    </select>
    <button onclick="add()">发送数据</button>
</body>
</html>
复制代码

首先在中间件中使用  app.UseWebSockets();

1
2
3
4
5
6
7
8
app.UseAuthorization();
 
app.UseWebSockets();
 
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});      

如何使用全局变量:在configService中注入

1
2
3
4
5
6
7
8
private readonly Dictionary<string, WebSocket> dic;
 
       //readonly static Dictionary<string, WebSocket> dic = new Dictionary<string, WebSocket>();
 
       public WeatherForecastController(Dictionary<string, WebSocket> dic)
       {
           this.dic = dic;
       }

后台代码演示

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
public class WeatherForecastController : ControllerBase
   {
       readonly static Dictionary<string, WebSocket> dic = new Dictionary<string, WebSocket>();
 
       [HttpGet("/ws")]
       public async Task Get()
       {
           if (HttpContext.WebSockets.IsWebSocketRequest)
           {
               //接受websocket客户端连接
               var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
               await Echo(webSocket, dic);
           }
           else
           {
               //不是websocket客户端请求
               HttpContext.Response.StatusCode = 400;
           }
       }
       /// <summary>
       /// 对客户端的处理,接受消息,发送消息,关闭连接
       /// </summary>
       /// <param name="webSocket"></param>
       /// <returns></returns>
       private async Task Echo(WebSocket webSocket, Dictionary<string, WebSocket> dic)
       {
           var buffer = new byte[1024 * 4];
           var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
           var user = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
           dic.Add(user, webSocket);
           while (!result.CloseStatus.HasValue)
           {
               var message = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
               if (message.Contains("***"))
               {
                   var msgArr = message.Split("***");
                   var msgDate = msgArr[0];
                   var msgTo = msgArr[1];
                   if (dic.ContainsKey(msgTo))
                   {
                       var webSocketGit = dic[msgTo];
                       //向客户端发送消息
                       await webSocketGit.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
                   }
                   else
                   {
                       throw new Exception("用户不存在");
                   }
               }
               else
               {
                   //向客户端发送消息
                   await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
               }
               //继续接受客户端消息
               result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
           }
           //关闭释放与客户端连接
           await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
       }
   }

  

posted @   电器小君子  阅读(466)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示