Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use C # to realize chat room function based on WebSocket

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to use C# to achieve chat room function based on WebSocket. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

ServerHelper:

Using System;using System.Collections;using System.Text;using System.Security.Cryptography; namespace SocketDemo {/ / Server assistant is responsible for: 1 handshake 2 request conversion 3 response conversion class ServerHelper {/ public static string ResponseHeader (string requestHeader) {Hashtable table = new Hashtable () / / split into key-value pairs and save to the hash table string [] rows = requestHeader.Split (new string [] {"\ r\ n"}, StringSplitOptions.RemoveEmptyEntries); foreach (string row in rows) {int splitIndex = row.IndexOf (':') If (splitIndex > 0) {table.Add (row.Substring (0, splitIndex) .Trim (), row.Substring (splitIndex + 1) .Trim ();}} StringBuilder header = new StringBuilder (); header.Append ("HTTP/1.1 101Web Socket Protocol Handshake\ r\ n") Header.AppendFormat ("Upgrade: {0}\ r\ n", table.ContainsKey ("Upgrade")? Table ["Upgrade"] .ToString (): string.Empty); header.AppendFormat ("Connection: {0}\ r\ n", table.ContainsKey ("Connection")? Table ["Connection"] .ToString (): string.Empty); header.AppendFormat ("WebSocket-Origin: {0}\ r\ n", table.ContainsKey ("Sec-WebSocket-Origin")? Table ["Sec-WebSocket-Origin"] .ToString (): string.Empty); header.AppendFormat ("WebSocket-Location: {0}\ r\ n", table.ContainsKey ("Host")? Table ["Host"] .ToString (): string.Empty); string key = table.ContainsKey ("Sec-WebSocket-Key")? Table ["Sec-WebSocket-Key"] .ToString (): string.Empty; string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; header.AppendFormat ("Sec-WebSocket-Accept: {0}\ r\ n", Convert.ToBase64String (SHA1.Create (). ComputeHash (key + magic); header.Append ("\ r\ n"); return header.ToString () } / decode the request content / 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) {Array.Copy (buffer, 4, mask, 0,4); payload_len = payload_len & 0x00000000 Payload_len = payload_len | buffer [2]; payload_len = (payload_len > 8 & 0xFF); Array.Copy (temp, 0, bts, 4, temp.Length) } else {byte [] st = System.Text.Encoding.UTF8.GetBytes (string.Format ("do not process extra long content") .ToCharArray ();} return bts;}}

Server:

Using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Net.Sockets; 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 clientList = new List () Public static void Add (ClientInfo info) {if (! IsExist (info.Address)) {clientList.Add (info);}} public static bool IsExist (string address) {return clientList.Exists (item = > string.Compare (address, item.Address, true) = = 0) } public static bool IsExist (string address, bool isOpen) {return clientList.Exists (item = > string.Compare (address, item.Address, true) = = 0 & & item.IsOpen = = isOpen) } public static void Open (string address) {clientList.ForEach (item = > {if (string.Compare (address, item.Address, true) = = 0) {item.IsOpen = true;}}) } public static void Close (string address = null) {clientList.ForEach (item = > {if (address = = null | | string.Compare (address, item.Address, true) = = 0) {item.IsOpen = false; item.Socket.Shutdown (SocketShutdown.Both) }) } / / send messages to ClientList public static void SendMsgToClientList (string msg, string address = null) {clientList.ForEach (item = > {if (item.IsOpen & & (address = = null | | item.Address! = address)) {SendMsgToClient (item.Socket, msg) }});} public static void SendMsgToClient (Socket client, string msg) {byte [] bt = ServerHelper.EncodeMsg (msg); client.BeginSend (bt, 0, bt.Length, SocketFlags.None, new AsyncCallback (SendTarget), client);} private static void SendTarget (IAsyncResult res) {/ / Socket client = (Socket) res.AsyncState / / int size = client.EndSend (res);}} / / receive message class ReceiveHelper {public byte [] Bytes {get; set;} public void ReceiveTarget (IAsyncResult res) {Socket client = (Socket) res.AsyncState; int size = client.EndReceive (res) If (size > 0) {string address = client.RemoteEndPoint.ToString (); / / get the IP and port of Client string stringdata = null; if (ClientManager.IsExist (address, false)) / / handshake {stringdata = Encoding.UTF8.GetString (Bytes, 0, size) ClientManager.SendMsgToClient (client, ServerHelper.ResponseHeader (stringdata)); ClientManager.Open (address);} else {stringdata = ServerHelper.DecodeMsg (Bytes, size) } if (stringdata.IndexOf ("exit") >-1) {ClientManager.SendMsgToClientList (address + "disconnected from server", address); ClientManager.Close (address); Console.WriteLine (address + "disconnected from server") Console.WriteLine (address + "" + DateTimeOffset.Now.ToString ("G")); return;} else {Console.WriteLine (stringdata); Console.WriteLine (address + "" + DateTimeOffset.Now.ToString ("G") ClientManager.SendMsgToClientList (stringdata, address);}} / continue waiting for client.BeginReceive (Bytes, 0, Bytes.Length, SocketFlags.None, new AsyncCallback (ReceiveTarget), client);}} / / listen for request class AcceptHelper {public byte [] Bytes {get; set } public void AcceptTarget (IAsyncResult res) {Socket server = (Socket) res.AsyncState; Socket client = server.EndAccept (res); string address = client.RemoteEndPoint.ToString (); ClientManager.Add (new ClientInfo () {Socket = client, Address = address, IsOpen = false}); ReceiveHelper rs = new ReceiveHelper () {Bytes = this.Bytes} IAsyncResult recres = client.BeginReceive (rs.Bytes, 0, rs.Bytes.Length, SocketFlags.None, new AsyncCallback (rs.ReceiveTarget), client); / / continue to monitor server.BeginAccept (new AsyncCallback (AcceptTarget), server);}} class Program {static void Main (string [] args) {Socket server = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) Server.Bind (new IPEndPoint (IPAddress.Parse ("127.0.0.1"), 200); / bind IP+ port server.Listen (10); / / start listening on Console.WriteLine ("waiting for connection..."); AcceptHelper ca = new AcceptHelper () {Bytes = new byte [2048]}; IAsyncResult res = server.BeginAccept (new AsyncCallback (ca.AcceptTarget), server) String str = string.Empty; while (str! = "exit") {str = Console.ReadLine (); Console.WriteLine ("ME:" + DateTimeOffset.Now.ToString ("G")); ClientManager.SendMsgToClientList (str);} ClientManager.Close (); server.Close () }}}

Client:

Var mySocket; function Star () {mySocket = new WebSocket ("ws://127.0.0.1:200", "my-custom-protocol"); mySocket.onopen = function Open () {Show ("connection open");}; mySocket.onmessage = function (evt) {Show (evt.data);} MySocket.onclose = function Close () {Show ("connection closed"); mySocket.close ();} function Send () {var content = document.getElementById ("content") .value; Show (content); mySocket.send (content);} function Show (msg) {var roomContent = document.getElementById ("roomContent") This is the end of the article on "how to use C # to implement chat room functions based on WebSocket". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report