How to write an application of asp.net as a websocket server

Recently, a problem with WebSockets has plagued me for a long time. One requirement is to set up a websocket service on a web site.The client establishes a connection with the server through a web page, and the server sends information to the client web page based on ip.

In fact, this requirement is not difficult, but at first you don't know much about the content of websocket s.I searched the internet, through asp.net core, through the general processing program ashx files, these methods can not meet the needs of my current website.

Finally, I achieved what I wanted with the fleck third-party library.Here's a more detailed description of my implementation.

1. Download the fleck third-party library, which I downloaded through Git. Source Download

Click Clone or download -> Download ZIP on the page to download

   

After downloading, you can view the document inside, and the specific implementation can view the code.

 

2. Add fleck to your project and reference it.

  

 

3. Write our own websocket class

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using Fleck;

namespace FAW.Common
{
    public class WsContext
    {
        //Client url And its corresponding Socket Object Dictionary
        static IDictionary<string, IWebSocketConnection> dic_Sockets = new Dictionary<string, IWebSocketConnection>();

        public static void StartUpWs()
        {
            String ipValue = ConfigurationManager.AppSettings["WebsocketAddress"];
            //Establish
            //WebSocketServer server = new WebSocketServer("ws://127.0.0.1:8819/terver");//Listen on all addresses
            WebSocketServer server = new WebSocketServer(ipValue);//The address to listen on is written in the profile
            //Restart after error
            server.RestartAfterListenError = true;

            //Start listening
            server.Start(socket =>
            {
                socket.OnOpen = () =>   //Connection Establishment Event
                {
                    //Get Client Page's url
                    string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    dic_Sockets.Add(clientUrl, socket);
                    LogManager.WriteLog("The server:And client web pages:[" + clientUrl + "] establish WebSock Connect!");
                };
                socket.OnClose = () =>  //Connection Close Event
                {
                    string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    //If this client exists,So for this socket Remove
                    if (dic_Sockets.ContainsKey(clientUrl))
                    {
                        //notes:Fleck Release in
                        //Close Object Connection 
                        if (dic_Sockets[clientUrl] != null)
                        {
                            dic_Sockets[clientUrl].Close();
                        }
                        dic_Sockets.Remove(clientUrl);
                    }
                    LogManager.WriteLog("The server:And client web pages:[" + clientUrl + "]  To break off WebSock Connect!");
                };
                socket.OnMessage = message =>  //Accept Client Web Page Message Events
                {
                    string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    LogManager.WriteLog("The server:[Received) To Client Web Page:" + clientUrl + "Information:\n" + message);

                };
            });

        }

        public static void SendMsg(String ipAddress, String jsonString)
        {
            if (String.IsNullOrEmpty(jsonString))
            {
                //Write a log
                LogManager.WriteLog("Abort sending, send message to client is empty." );
                return;
            }
            foreach (var item in dic_Sockets.Values)
            {
                if (item.IsAvailable == true && item.ConnectionInfo.ClientIpAddress == ipAddress)
                {
                    LogManager.WriteLog("The server: Send information to client as " + jsonString);
                    item.Send(jsonString);
                }
            }
        }
    }
}

 

In this code, the StartUpWs function mainly establishes a websocket server, and the SendMsg function is responsible for providing external calls to send content to the specified client.

            try
            {
                String pdaIP = cameraLogic.QueryPDAIPByIP(cameraIP);
                LogManager.WriteLog("Get the phone corresponding to the camera IP: " + pdaIP);
                WsContext.SendMsg(pdaIP, sendMessage);
            }
            catch (Exception ex)
            {
                LogManager.WriteLog("Manual lifting lever websocket Exception:" + ex.Message);
            }            

This code snippet calls the SendMsg function in the website to send data to the specified client.

Note: It is important to note that if the ports of the websocket service are to be accessed by an external network, the ports need to be added to the firewall inbound rules, and the ip and port mapping between the internal network and the external network is required, otherwise the external network will not be able to access the service.

4. Next, we'll add a websocket to the website so that it starts when the website starts.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Security;
using FAW.WEB;
using FAW.Common;

namespace FAW.WEB
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs at application startup
            AuthConfig.RegisterOpenAuth();

            //establish websocket The server
            WsContext.StartUpWs();
        }
        
    }
}

This is OK.

5. Testing the websocket service, if available, can pass the websocket online testing function.As long as you look at Baidu, you will know all about it. It is very simple. It will not be introduced here anymore.

Summary: In fact, the operation of WebSockets is really difficult, that is, after an upgrade of ordinary http requests, a full-duplex channel is set up to send messages to each other.I just can't find an example of asp.net website as a server on the Internet. In fact, there are only two steps to do: 1. Set up a server of websocket; 2. Add the server of websocket to the Global file and start with the program.I'll share this, hoping to help more people.

Keywords: ASP.NET socket network git firewall

Added by markmil2002 on Fri, 14 Feb 2020 05:44:02 +0200