当前位置:网站首页>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 !
边栏推荐
- I stepped on a foundation pit today
- 15. System limitations and options
- The difference between int (1) and int (10)
- Summarize the past to motivate yourself to move on
- 60 year old people buy medical insurance and recommend a better product
- Final consistency of MESI cache in CPU -- why does CPU need cache
- Properties of binary trees (numerical aspects)
- 3D game modeling is in full swing. Are you still confused about the future?
- Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
- The "two-way link" of pushing messages helps app quickly realize two-way communication capability
猜你喜欢

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

96% of the collected traffic is prevented by bubble mart of cloud hosting

Database concept and installation

16. System and process information
![[Yugong series] February 2022 attack and defense world advanced question misc-84 (MySQL)](/img/4d/4a6b76896bf81a27d036a047f68b2b.jpg)
[Yugong series] February 2022 attack and defense world advanced question misc-84 (MySQL)

1day vulnerability pushback skills practice (3)

Chain ide -- the infrastructure of the metauniverse

There is no need to authorize the automatic dream weaving collection plug-in for dream weaving collection

Push technology practice | master these two tuning skills to speed up tidb performance a thousand times!

17. File i/o buffer
随机推荐
150 ppt! The most complete "fair perception machine learning and data mining" tutorial, Dr. AIST Toshihiro kamishima, Japan
機器學習基礎:用 Lasso 做特征選擇
Li Chuang EDA learning notes 13: electrical network for drawing schematic diagram
Osnabrueck University | overview of specific architectures in the field of reinforcement learning
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
Global and Chinese market for travel wheelchairs 2022-2028: Research Report on technology, participants, trends, market size and share
Yyds dry goods inventory override and virtual of classes in C
String: LV1 eat hot pot
Short math guide for latex by Michael downs
Sword finger offer 14- I. cut rope
The reasons why QT fails to connect to the database and common solutions
在尋求人類智能AI的過程中,Meta將賭注押向了自監督學習
[development team follows] API specification
Valentine's Day - 9 jigsaw puzzles with deep love in wechat circle of friends
C learning notes: C foundation - Language & characteristics interpretation
Experience summary of the 12th Blue Bridge Cup (written for the first time)
長文綜述:大腦中的熵、自由能、對稱性和動力學
What are the conditions for the opening of Tiktok live broadcast preview?
STM32 key content
Override and virtual of classes in C #