ASP.NET CORE使用websocket

原创 Laughing  2017-09-06 09:16  阅读 91 次 评论 1 条

文档参考

安装Microsoft.AspNetCore.WebSockets

如果使用Nuget Manager,直接执行Install-Package Microsoft.AspNetCore.WebSockets -Version 2.0.0安装

如果使用VSCode,可以在终端执行dotnet add package Microsoft.AspNetCore.WebSockets --version 2.0.0安装

配置中间件

  1. var websocketsOption = new WebSocketOptions(){  
  2.                 KeepAliveInterval = TimeSpan.FromSeconds(120),  
  3.                 ReceiveBufferSize = 4*1024  
  4.             };  
  5.             app.UseWebSockets(websocketsOption);  
配置服务端请求以及响应方法
  1. app.Use(async(context,next)=>{  
  2.                 if(context.Request.Path == "/ws"){  
  3.                     if(context.WebSockets.IsWebSocketRequest){//websocket请求  
  4.                         WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();  
  5.                         await Echo(context,socket);  
  6.                     }else{  
  7.                         context.Response.StatusCode = 400;  
  8.                     }  
  9.                 }else{  
  10.                     await next();  
  11.                 }  
  12.             });  
  1. private async Task Echo(HttpContext context,WebSocket socket){  
  2.             var buffer = new byte[4*1024];  
  3.             WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer),CancellationToken.None);  
  4.             while(!result.CloseStatus.HasValue){  
  5.                 await socket.SendAsync(new ArraySegment<byte>(buffer,0,result.Count),result.MessageType,result.EndOfMessage,CancellationToken.None);  
  6.                 result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer),CancellationToken.None);  
  7.             }  
  8.             await socket.CloseAsync(result.CloseStatus.Value,result.CloseStatusDescription,CancellationToken.None);  
  9.         }  

发送和接收消息

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <title>WebSocket简单示例</title>  
  7.     <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>  
  8.     <script src="http://apps.bdimg.com/libs/bootstrap/3.3.4/js/bootstrap.js"></script>  
  9.   
  10.   
  11.     <link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.4/css/bootstrap.css">  
  12.     <link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.4/css/bootstrap-theme.css">  
  13.     <style>  
  14.         button {  
  15.             margin-top: 10px;  
  16.         }  
  17.           
  18.         table {  
  19.             border: 0  
  20.         }  
  21.           
  22.         .commslog-data {  
  23.             font-family: Consolas, Courier New, Courier, monospace;  
  24.             background-color: yellowgreen;  
  25.             color: white  
  26.         }  
  27.           
  28.         .commslog-server {  
  29.             background-color: red;  
  30.             color: white  
  31.         }  
  32.           
  33.         .commslog-client {  
  34.             background-color: green;  
  35.             color: white  
  36.         }  
  37.     </style>  
  38. </head>  
  39.   
  40. <body>  
  41.     <h1>WebSocket简单示例</h1>  
  42.     <p class="text" id="stateLabel">准备连接...</p>  
  43.     <div>  
  44.         <label class="control-label" for="connectionUrl">WebSocket服务器地址:</label>  
  45.         <input class="form-control" id="connectionUrl" />  
  46.         <button id="connectButton" type="submit" class="btn btn-success">连接</button>  
  47.     </div>  
  48.     <p></p>  
  49.     <div>  
  50.         <label for="sendMessage" class="control-label">消息:</label>  
  51.         <input id="sendMessage" class="form-control" />  
  52.         <button id="sendButton" type="submit" class="btn btn-default">发送</button>  
  53.         <button id="closeButton" class="btn btn-danger">关闭连接</button>  
  54.     </div>  
  55.   
  56.     <h2>消息</h2>  
  57.     <table style="width: 800px">  
  58.         <thead>  
  59.             <tr>  
  60.                 <td style="width: 100px">From</td>  
  61.                 <td style="width: 100px">To</td>  
  62.                 <td>Data</td>  
  63.             </tr>  
  64.         </thead>  
  65.         <tbody id="commsLog">  
  66.         </tbody>  
  67.     </table>  
  68.   
  69.     <script>  
  70.         var webSocket;  
  71.         $(function() {  
  72.             $("#connectionUrl").val(window.location.href.replace("http""ws").replace("index.html""ws"));  
  73.             //连接按钮  
  74.             $("#connectButton").click(function() {  
  75.                 webSocket = new WebSocket($("#connectionUrl").val());  
  76.                 webSocket.onopen = function() {  
  77.                     $("#stateLabel").text('连接成功');  
  78.                     $("#stateLabel").css('color', 'green');  
  79.                 };  
  80.                 webSocket.onclose = function() {  
  81.                     $("#stateLabel").text('连接关闭');  
  82.                     $("#stateLabel").css('color', 'gray');  
  83.                 };  
  84.                 webSocket.onmessage = function(e) {  
  85.                     $("#commsLog").append("<tr><td class='commslog-client'>client</td><td class='commslog-server'>server</td><td class='commslog-data'>" + $("#sendMessage").val() + "</td></tr>");  
  86.                     $("#commsLog").append("<tr><td class='commslog-server'>server</td><td class='commslog-client'>client</td><td class='commslog-data'>" + e.data + "</td></tr>");  
  87.                 };  
  88.             });  
  89.             //关闭连接  
  90.             $("#closeButton").click(function() {  
  91.                 webSocket.close();  
  92.             });  
  93.             //发送消息  
  94.             $("#sendButton").click(function() {  
  95.                 webSocket.send($("#sendMessage").val());  
  96.             });  
  97.         });  
  98.     </script>  
  99. </body>  
  100.   
  101. </html>  

本文地址:https://www.lisen.me/asp-net-core-websocket.html
版权声明:本文为原创文章,版权归 木子网 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

  1. 快乐赚
    快乐赚 【农民】 @回复

    这个博客不简单,看了还想接着看。