当前位置:网站首页>How to use websocket to realize simple chat function in C #
How to use websocket to realize simple chat function in C #
2022-07-04 02:49:00 【Yisu cloud】
C# How to use it websocket Realize simple chat function
This article mainly explains “C# How to use it websocket Realize simple chat function ”, Interested friends might as well come and have a look . The method introduced in this paper is simple and fast , Practical . Now let Xiaobian take you to learn “C# How to use it websocket Realize simple chat function ” Well !
Preface
Use C# Language development , be based on .NET FrameWork4
The function includes group chat , Talk privately with
Interface
Interface design code
namespace chat_server { partial class Form1 { /// <summary> /// Required designer variables . /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up all the resources in use . /// </summary> /// <param name="disposing"> If managed resources should be released , by true; Otherwise false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form designer generated code /// <summary> /// The designer supports the required methods - Do not modify /// Use the code editor to modify the contents of this method . /// </summary> private void InitializeComponent() { this.textBoxIP = new System.Windows.Forms.TextBox(); this.labelIP = new System.Windows.Forms.Label(); this.labelPort = new System.Windows.Forms.Label(); this.textBoxPort = new System.Windows.Forms.TextBox(); this.buttonStart = new System.Windows.Forms.Button(); this.textBoxLog = new System.Windows.Forms.TextBox(); this.textBoxMsg = new System.Windows.Forms.TextBox(); this.buttonSend = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBoxIP // this.textBoxIP.Location = new System.Drawing.Point(145, 25); this.textBoxIP.Name = "textBoxIP"; this.textBoxIP.Size = new System.Drawing.Size(100, 25); this.textBoxIP.TabIndex = 0; this.textBoxIP.Text = "127.0.0.1"; // // labelIP // this.labelIP.AutoSize = true; this.labelIP.Location = new System.Drawing.Point(90, 28); this.labelIP.Name = "labelIP"; this.labelIP.Size = new System.Drawing.Size(31, 15); this.labelIP.TabIndex = 1; this.labelIP.Text = "IP:"; // // labelPort // this.labelPort.AutoSize = true; this.labelPort.Location = new System.Drawing.Point(371, 28); this.labelPort.Name = "labelPort"; this.labelPort.Size = new System.Drawing.Size(54, 15); this.labelPort.TabIndex = 3; this.labelPort.Text = "port:"; // // textBoxPort // this.textBoxPort.Location = new System.Drawing.Point(452, 25); this.textBoxPort.Name = "textBoxPort"; this.textBoxPort.Size = new System.Drawing.Size(100, 25); this.textBoxPort.TabIndex = 2; this.textBoxPort.Text = "6666"; // // buttonStart // this.buttonStart.Location = new System.Drawing.Point(718, 13); this.buttonStart.Name = "buttonStart"; this.buttonStart.Size = new System.Drawing.Size(142, 45); this.buttonStart.TabIndex = 4; this.buttonStart.Text = " Opening service "; this.buttonStart.UseVisualStyleBackColor = true; this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click); // // textBoxLog // this.textBoxLog.Location = new System.Drawing.Point(28, 73); this.textBoxLog.Multiline = true; this.textBoxLog.Name = "textBoxLog"; this.textBoxLog.Size = new System.Drawing.Size(832, 406); this.textBoxLog.TabIndex = 5; // // textBoxMsg // this.textBoxMsg.Location = new System.Drawing.Point(28, 499); this.textBoxMsg.Name = "textBoxMsg"; this.textBoxMsg.Size = new System.Drawing.Size(653, 25); this.textBoxMsg.TabIndex = 6; // // buttonSend // this.buttonSend.Location = new System.Drawing.Point(761, 499); this.buttonSend.Name = "buttonSend"; this.buttonSend.Size = new System.Drawing.Size(99, 43); this.buttonSend.TabIndex = 7; this.buttonSend.Text = " send out "; this.buttonSend.UseVisualStyleBackColor = true; this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(947, 567); this.Controls.Add(this.buttonSend); this.Controls.Add(this.textBoxMsg); this.Controls.Add(this.textBoxLog); this.Controls.Add(this.buttonStart); this.Controls.Add(this.labelPort); this.Controls.Add(this.textBoxPort); this.Controls.Add(this.labelIP); this.Controls.Add(this.textBoxIP); this.Name = "Form1"; this.Text = " The server "; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBoxIP; private System.Windows.Forms.Label labelIP; private System.Windows.Forms.Label labelPort; private System.Windows.Forms.TextBox textBoxPort; private System.Windows.Forms.Button buttonStart; private System.Windows.Forms.TextBox textBoxLog; private System.Windows.Forms.TextBox textBoxMsg; private System.Windows.Forms.Button buttonSend; } }
Source code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace chat_server { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } // socket Connect the container Dictionary<Socket, String> userContain = new Dictionary<Socket, string>(); private void buttonStart_Click(object sender, EventArgs e) { try { //1、 establish socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2、 binding ip And port String ip = textBoxIP.Text; int port = Convert.ToInt32(textBoxPort.Text); socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); //3、 Turn on monitoring socket.Listen(10);// The maximum value of waiting for connection queue //4、 Start accepting client links ThreadPool.QueueUserWorkItem(new WaitCallback(connect), socket); } catch { MessageBox.Show(" Failed to start the server "); } } private void connect(object socket) { var serverSockert = socket as Socket;// Coercive transformation showLog(" The server starts normally , Start accepting data from the client "); byte[] data = new byte[1024]; int len; String name; // The user name of the client while (true) { try { var proxSocket = serverSockert.Accept();// Accept the connection len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);// Accept the user name of the client name = Encoding.Default.GetString(data, 0, len); showLog(String.Format(" client {0} user name {1} Connect to server ", proxSocket.RemoteEndPoint.ToString(),name)); String msg = String.Format(" user {0} launched ", name); sendMsg(msg); userContain[proxSocket] = name;// Put the object into the collection // Constantly accept the messages sent by the currently linked client ThreadPool.QueueUserWorkItem(new WaitCallback(this.recevie), proxSocket); } catch { MessageBox.Show(" Accept exceptions "); break; } } } private void recevie(object socket) { var proxSocket = socket as Socket; byte[] data = new byte[1024 * 1024];// Accept , Send data buffer String msg; int len = 0; // Data length String name = userContain[proxSocket]; // Client name while (true) { try { len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None); } catch { msg = String.Format(" client {0} Abnormal exit ", proxSocket.RemoteEndPoint.ToString()); showLog(msg); msg = String.Format(" user {0} Get offline ", name); sendMsg(msg); userContain.Remove(proxSocket); stopConnect(proxSocket); return; } if (len <= 0) { // The client exits normally msg = String.Format(" client {0} The normal exit ", proxSocket.RemoteEndPoint.ToString()); showLog(msg); msg = String.Format(" user {0} Get offline ", name); sendMsg(msg); userContain.Remove(proxSocket); stopConnect(proxSocket); return;// End the asynchronous thread that currently accepts client data } // Receive a message msg = Encoding.Default.GetString(data, 0, len); // Format of private chat information @name:msg //name Username msg For message bool flag = true; if (msg.StartsWith("@")) { int index = msg.IndexOf(":"); String targetName = msg.Substring(1, index-1); msg = msg.Substring(index + 1); foreach(var user in userContain) { if(targetName.Equals(user.Value)&&user.Key.Connected) { msg = String.Format(" user {0} To you alone :{1}",name,msg); data = Encoding.Default.GetBytes(msg); user.Key.Send(data, 0, data.Length, SocketFlags.None); flag = false; break; } } } if (flag) { msg = String.Format(" user {0}:{1}", name, msg); sendMsg(msg); } } } private void stopConnect(Socket socket) { try { if (socket.Connected) { socket.Shutdown(SocketShutdown.Both); socket.Close(100); } } catch { } } private void showLog(String msg) { if (textBoxLog.InvokeRequired) { // If it is cross thread access textBoxLog.Invoke(new Action<String>( s => { this.textBoxLog.Text += msg+"\r\n"; }),msg); } else { this.textBoxLog.Text += msg; } } private void buttonSend_Click(object sender, EventArgs e) { // Send a message String msg = String.Format(" The server issues notification information {0}", textBoxMsg.Text); sendMsg(msg); } private void sendMsg(String msg) { byte[] data = new byte[1024 * 1024]; data = Encoding.Default.GetBytes(msg); foreach (var user in userContain) { if (user.Key.Connected) { user.Key.Send(data, 0, data.Length, SocketFlags.None); } } } } }
Here we are , I'm sure you're right “C# How to use it websocket Realize simple chat function ” Have a deeper understanding of , You might as well put it into practice ! This is the Yisu cloud website , For more relevant contents, you can enter the relevant channels for inquiry , Pay attention to our , Continue to learn !
边栏推荐
- A. Div. 7
- Amélioration de l'efficacité de la requête 10 fois! 3 solutions d'optimisation pour résoudre le problème de pagination profonde MySQL
- Keepalived set the master not to recapture the VIP after fault recovery (it is invalid to solve nopreempt)
- Pytoch residual network RESNET
- A brief talk on professional modeler: the prospect and professional development of 3D game modeling industry in China
- C language black Technology: Archimedes spiral! Novel, interesting, advanced~
- Short math guide for latex by Michael downs
- Sword finger offer 14- I. cut rope
- Johnson–Lindenstrauss Lemma
- VRRP+BFD
猜你喜欢
WordPress collection WordPress hang up collection plug-in
3D game modeling is in full swing. Are you still confused about the future?
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
Push technology practice | master these two tuning skills to speed up tidb performance a thousand times!
Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami
The first spring of the new year | a full set of property management application templates are presented, and Bi construction is "out of the box"
There is no need to authorize the automatic dream weaving collection plug-in for dream weaving collection
The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult
Comment la transformation numérique du crédit d'information de la Chine passe - t - elle du ciel au bout des doigts?
I stepped on a foundation pit today
随机推荐
Résumé des outils communs et des points techniques de l'examen PMP
Global and Chinese market of small batteries 2022-2028: Research Report on technology, participants, trends, market size and share
Idea if a class cannot be found, it will be red
(column 23) typical C language problem: find the minimum common multiple and maximum common divisor of two numbers. (two solutions)
Practical multifunctional toolbox wechat applet source code / support traffic master
The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult
Career development direction
Safety tips - seat belt suddenly fails to pull? High speed police remind you how to use safety belts in a standardized way
Hamburg University of Technology (tuhh) | intelligent problem solving as integrated hierarchical reinforcement learning
The difference between int (1) and int (10)
Contest3145 - the 37th game of 2021 freshman individual training match_ E: Eat watermelon
Global and Chinese markets of advanced X-ray inspection system (Axi) in PCB 2022-2028: Research Report on technology, participants, trends, market size and share
Jenkins continuous integration environment construction V (Jenkins common construction triggers)
Hospital network planning and design document based on GLBP protocol + application form + task statement + opening report + interim examination + literature review + PPT + weekly progress + network to
Sword finger offer 14- I. cut rope
Basé sur... Netcore Development blog Project Starblog - (14) Implementation of theme switching function
Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami
96% of the collected traffic is prevented by bubble mart of cloud hosting
Gee import SHP data - crop image
Hunan University | robust Multi-Agent Reinforcement Learning in noisy environment