How to use websocket to realize simple chat function in C #
This article mainly explains "how to use websocket to achieve simple chat function in C#", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to use websocket to achieve simple chat function in C#"!
Preface
Develop in C # language, based on .NET FrameWork4
The functions include group chat and private chat.
Interface
Interface design code
Namespace chat_server {partial class Form1 {/ required designer variables. / private System.ComponentModel.IContainer components = null; / Clean up all resources in use. / if the managed resource should be released, true; otherwise false. Protected override void Dispose (bool disposing) {if (disposing & & (components! = null)) {components.Dispose ();} base.Dispose (disposing) The code generated by the region Windows forms designer supports the required method-do not modify / modify the contents of this method using the code editor. / / 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 = "enable 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 (28499); 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"; 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 = "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 connection container Dictionary userContain = new Dictionary () Private void buttonStart_Click (object sender, EventArgs e) {try {/ / 1, create socket Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); / / 2, bind ip and port String ip = textBoxIP.Text Int port = Convert.ToInt32 (textBoxPort.Text); socket.Bind (new IPEndPoint (IPAddress.Parse (ip), port)); / / 3. Enable the listening socket.Listen (10); / / wait for the maximum value of the connection queue / / 4, and start accepting the link ThreadPool.QueueUserWorkItem from the client (new WaitCallback (connect), socket) } catch {MessageBox.Show ("failed to start the server");}} private void connect (object socket) {var serverSockert = socket as Socket;// cast showLog ("the server starts normally and starts to accept data from the client") Byte [] data = new byte [1024]; user name of int len; String name; / / client while (true) {try {var proxSocket = serverSockert.Accept () / / accept connection len = proxSocket.Receive (data, 0, data.Length, SocketFlags.None); / / accept client user name name = Encoding.Default.GetString (data, 0, len); showLog ("client {0} username {1} connect to server", proxSocket.RemoteEndPoint.ToString (), name)) String msg = String.Format ("user {0} is online", name); sendMsg (msg); userContain [proxSocket] = name;// puts objects into the collection / / constantly accepts 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} offline", name) SendMsg (msg); userContain.Remove (proxSocket); stopConnect (proxSocket); return;} if (len {this.textBoxLog.Text + = msg+ "\ r\ n";}), msg) } else {this.textBoxLog.Text + = msg;}} private void buttonSend_Click (object sender, EventArgs e) {/ / send message String msg = String.Format ("Server Post 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) At this point, I believe you have a deeper understanding of "how to use websocket to achieve simple chat function in C#". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!