SoFunction
Updated on 2025-03-07

C# implements chat room functions based on WebSocket

This article shares the specific code of C#’s chat room function based on WebSocket for your reference. The specific content is as follows

Review the previous two articles, C# Socket content

This chapter is modified into a WebSocket chat room based on Socket asynchronous chat room

The special features of WebSocket are the encoding and decoding of handshake and message content (the serverHelper has been added to assist in processing)

ServerHelper:

using System;
using ;
using ;
using ;
 
namespace SocketDemo
{
    // Server Assistant is responsible for: 1 Handshake 2 Request conversion 3 Response conversion    class ServerHelper
    {
        /// <summary>
        /// Output connection header information        /// </summary>
        public static string ResponseHeader(string requestHeader)
        {
            Hashtable table = new Hashtable();
 
            // Split into key-value pairs and save to hash table            string[] rows = (new string[] { "\r\n" }, );
            foreach (string row in rows)
            {
                int splitIndex = (':');
                if (splitIndex > 0)
                {
                    ((0, splitIndex).Trim(), (splitIndex + 1).Trim());
                }
            }
 
            StringBuilder header = new StringBuilder();
            ("HTTP/1.1 101 Web Socket Protocol Handshake\r\n");
            ("Upgrade: {0}\r\n", ("Upgrade") ? table["Upgrade"].ToString() : );
            ("Connection: {0}\r\n", ("Connection") ? table["Connection"].ToString() : );
            ("WebSocket-Origin: {0}\r\n", ("Sec-WebSocket-Origin") ? table["Sec-WebSocket-Origin"].ToString() : );
            ("WebSocket-Location: {0}\r\n", ("Host") ? table["Host"].ToString() : );
 
            string key = ("Sec-WebSocket-Key") ? table["Sec-WebSocket-Key"].ToString() : ;
            string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            ("Sec-WebSocket-Accept: {0}\r\n", Convert.ToBase64String(().ComputeHash((key + magic))));
 
            ("\r\n");
 
            return ();
        }
 
        /// <summary>
        /// Decode the requested content        /// </summary>
        public static string DecodeMsg(Byte[] buffer, int len)
        {
            if (buffer[0] != 0x81
                || (buffer[0] & 0x80) != 0x80
                || (buffer[1] & 0x80) != 0x80)
            {
                return null;
            }
            Byte[] mask = new Byte[4];
            int beginIndex = 0;
            int payload_len = buffer[1] & 0x7F;
            if (payload_len == 0x7E)
            {
                (buffer, 4, mask, 0, 4);
                payload_len = payload_len & 0x00000000;
                payload_len = payload_len | buffer[2];
                payload_len = (payload_len << 8) | buffer[3];
                beginIndex = 8;
            }
            else if (payload_len != 0x7F)
            {
                (buffer, 2, mask, 0, 4);
                beginIndex = 6;
            }
 
            for (int i = 0; i < payload_len; i++)
            {
                buffer[i + beginIndex] = (byte)(buffer[i + beginIndex] ^ mask[i % 4]);
            }
            return Encoding.(buffer, beginIndex, payload_len);
        }
 
        /// <summary>
        /// Encode the response content        /// </summary>
        public static byte[] EncodeMsg(string content)
        {
            byte[] bts = null;
            byte[] temp = Encoding.(content);
            if ( < 126)
            {
                bts = new byte[ + 2];
                bts[0] = 0x81;
                bts[1] = (byte);
                (temp, 0, bts, 2, );
            }
            else if ( < 0xFFFF)
            {
                bts = new byte[ + 4];
                bts[0] = 0x81;
                bts[1] = 126;
                bts[2] = (byte)( & 0xFF);
                bts[3] = (byte)( >> 8 & 0xFF);
                (temp, 0, bts, 4, );
            }
            else
            {
                byte[] st = .(("Not processed for the time being").ToCharArray());
            }
            return bts;
        }
    }
}

Server:

using System;
using ;
using ;
using ;
using ;
 
namespace SocketDemo
{
    class ClientInfo
    {
        public Socket Socket { get; set; }
        public bool IsOpen { get; set; }
        public string Address { get; set; }
    }
 
    // Manage Client    class ClientManager
    {
        static List<ClientInfo> clientList = new List<ClientInfo>();
        public static void Add(ClientInfo info)
        {
            if (!IsExist())
            {
                (info);
            }
        }
        public static bool IsExist(string address)
        {
            return (item => (address, , true) == 0);
        }
        public static bool IsExist(string address, bool isOpen)
        {
            return (item => (address, , true) == 0 &&  == isOpen);
        }
        public static void Open(string address)
        {
            (item =>
            {
                if ((address, , true) == 0)
                {
                     = true;
                }
            });
        }
        public static void Close(string address = null)
        {
            (item =>
            {
                if (address == null || (address, , true) == 0)
                {
                     = false;
                    ();
                }
            });
        }
        // Send a message to ClientList        public static void SendMsgToClientList(string msg, string address = null)
        {
            (item =>
            {
                if ( && (address == null ||  != address))
                {
                    SendMsgToClient(, msg);
                }
            });
        }
        public static void SendMsgToClient(Socket client, string msg)
        {
            byte[] bt = (msg);
            (bt, 0, , , new AsyncCallback(SendTarget), client);
        }
        private static void SendTarget(IAsyncResult res)
        {
            //Socket client = (Socket);
            //int size = (res);
        }
    }
 
    // Receive message    class ReceiveHelper
    {
        public byte[] Bytes { get; set; }
        public void ReceiveTarget(IAsyncResult res)
        {
            Socket client = (Socket);
            int size = (res);
            if (size > 0)
            {
                string address = (); // Get the client's IP and port                string stringdata = null;
                if ((address, false)) // Handshake                {
                    stringdata = Encoding.(Bytes, 0, size);
                    (client, (stringdata));
                    (address);
                }
                else
                {
                    stringdata = (Bytes, size);
                }
                if (("exit") > -1)
                {
                    (address + "Disconnected from server", address);
                    (address);
                    (address + "Disconnected from server");
                    (address + " " + ("G"));
                    return;
                }
                else
                {
                    (stringdata);
                    (address + " " + ("G"));
                    (stringdata, address);
                }
            }
            // Keep waiting            (Bytes, 0, , , new AsyncCallback(ReceiveTarget), client);
        }
    }
 
    // Listen to requests    class AcceptHelper
    {
        public byte[] Bytes { get; set; }
 
        public void AcceptTarget(IAsyncResult res)
        {
            Socket server = (Socket);
            Socket client = (res);
            string address = ();
 
            (new ClientInfo() { Socket = client, Address = address, IsOpen = false });
            ReceiveHelper rs = new ReceiveHelper() { Bytes =  };
            IAsyncResult recres = (, 0, , , new AsyncCallback(), client);
            // Continue to monitor            (new AsyncCallback(AcceptTarget), server);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Socket server = new Socket(, , );
            (new IPEndPoint(("127.0.0.1"), 200)); // Bind IP+ port            (10); // Start monitoring 
            ("Waiting for connection...");
 
            AcceptHelper ca = new AcceptHelper() { Bytes = new byte[2048] };
            IAsyncResult res = (new AsyncCallback(), server);
 
            string str = ;
            while (str != "exit")
            {
                str = ();
                ("ME: " + ("G"));
                (str);
            }
            ();
            ();
        }
    }
}

Client:

<!DOCTYPE html>
<script>
    var mySocket;
    function Star() {
        mySocket = new WebSocket("ws://127.0.0.1:200", "my-custom-protocol");
         = function Open() {
            Show("Connection open");
        };
         = function (evt) {
            Show();
        };
         = function Close() {
            Show("Connection Close");
            ();
        };
    }
    function Send() {
        var content = ("content").value;
        Show(content);
        (content);
    }
    function Show(msg) {
        var roomContent = ("roomContent");
         = msg + "<br/>" + ;
    }
</script>
<html>
<head>
    <title></title>
</head>
<body>
    <div  style="width: 500px; height: 200px; overflow: hidden; border: 2px solid #686868;
        margin-bottom: 10px; padding: 10px 0px 0px 10px;">
    </div>
    <div>
        <textarea  cols="50" rows="3" style="padding: 10px 0px 0px 10px;"></textarea>
    </div>
    <input type="button" value="Connection" οnclick="Star()" />
    <input type="button" value="Send" οnclick="Send()" />
</body>
</html>

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.