1024programmer Asp.Net .Net MVC implements WebSocket

.Net MVC implements WebSocket

.Net MVC implements WebSocket

WebSockets

WebSocket

1. Based on Html5, IIS8.0 or above, both the front-end code and the server must support WebSocket to be used;

2. The request must start with WS:

The following is the method for receiving front-end websocket applications in the background:

/// 
         /// WebSocket method of establishing a link
         /// 
         /// 
         public void MyWebSocket(  string name)
         {
             //MVC  There is an attribute IsWebSocketRequest in the context to see if it is currently a websocket
             if (HttpContext.IsWebSocketRequest)
             {
                 this.UserName =  name;
                 //If yes  websocket, then you need to specify a delegate and pass the method ProcessChat as a parameter into AcceptWebSocketRequest for execution.  
  HttpContext.AcceptWebSocketRequest(ProcessChat);
             }
             else
             {
                 HttpContext.Response.Write("I don’t handle it");
             }
         }

From the above code, we can know that the requested connection must be a websocket, otherwise it will not be processed. If I call this method through the URL on my browser instead of calling it by creating a websocket object, the following results will appear:

If it is called from a websocket object, it will work:

 var url = "ws://localhost:57211/Home/MyWebSocket";
         var socket;
         function connect() {
             var webSocketUrl = url + "?name=" + $("#userName").val();
             //Note:  After the following line of code is executed, it has been transferred to the MyWebSocket method in the background.  
             socket = new WebSocket(webSocketUrl)
         }

You can execute the custom ProcessChat method in the background. This method specifically handles the transaction logic related to websocket connections. For example, if a message is sent from the front end and a reply is received from the back end:

 public async Task ProcessChat(AspNetWebSocketContext socketContext)
         {
             //socketContext.  What WebSocket obtains here is a websocket object information sent from the current browser to the server. Through this object, the information can be processed during the current connection.
             System.Net.WebSockets.WebSocket socket = socketContext.WebSocket;
             ArraySegment<<span style="color://If  Empty means that this websocket object instance has not been allocated and is not online.  
                 if (socketInfo.Socket == null  )
                 {
                     #region The chatList stores offline personnel. Information is stored here and can be received after the offline personnel come online.  to information

                     //This is mainly responsible for offline messages  , ensure that newly logged-in users can see previous messages,
                     //Then look  Check whether the user is in the list of objects to be sent. If so, the message will be temporarily stored in the information corresponding to the user. If the user comes online, all the data can be sent to him.  Of course, you can also store these data in the database, but it is not very good. It is better to put it in redis, nosql, or MongoDb.  
                     if (chatList.ContainsKey(socketInfo.  UserName))
                     {
                         chatList[socketInfo.UserName].Add(buffer);
                     }
                     else
                     {
                         chatList.Add(socketInfo.UserName, new List<ArraySegment<byte>>() { buffer });
                     }

                     #endregion
                 }
                 else
                 {
                     await socketInfo.Socket.SendAsync(buffer, WebSocketMessageType.Text, true, token);
                 }
             }

         }
         /// 
         /// This does not matter whether the offline message is currently  User comes in
         /// 
         /// 
         /// 
         /// 
         /// 
         public static async Task Say(CancellationToken token, string  span> userName, string content)
         {
             ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[2048]);
             buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes($"{DateTime.Now.ToString("yyyy year MM month dd day HH  :mm:ss:fff")  }{userName}:{content}"));

             foreach (var socketInfo in socketlist)
             {
                 if (socketInfo.Socket != null)
                 {
                     await socketInfo.Socket.SendAsync(buffer, WebSocketMessageType.Text, true, token);
                 }
             }

         }
     }

Result:

Heartbeat packets and disconnection reconnection

Reconnecting automatically reconnects after disconnection

zhuangzai:

https://www.cnblogs.com/anjingdian/p/15327526.html

span style=”color: rgba(0, 0, 255, 1)”>var socketInfo in socketlist)
{
if (socketInfo.Socket != null)
{
await socketInfo.Socket.SendAsync(buffer, WebSocketMessageType.Text, true, token);
}
}

}
}

Result:

Heartbeat packets and disconnection reconnection

Reconnecting automatically reconnects after disconnection

zhuangzai:

https://www.cnblogs.com/anjingdian/p/15327526.html

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/net-mvc-implements-websocket-2/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索