当前位置:网站首页>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 !
边栏推荐
- Fudan released its first review paper on the construction and application of multimodal knowledge atlas, comprehensively describing the existing mmkg technology system and progress
- Key knowledge of embedded driver
- Unity controls the selection of the previous and next characters
- Is online futures account opening safe and reliable? Which domestic futures company is better?
- Keep an IT training diary 054- opening and closing
- 中電資訊-信貸業務數字化轉型如何從星空到指尖?
- C language black Technology: Archimedes spiral! Novel, interesting, advanced~
- Crawler practice website image batch download
- [software implementation series] software implementation interview questions with SQL joint query diagram
- Pytoch residual network RESNET
猜你喜欢

Problems and solutions of several concurrent scenarios of redis

Li Chuang EDA learning notes IX: layers

The boss said: whoever wants to use double to define the amount of goods, just pack up and go

150 ppt! The most complete "fair perception machine learning and data mining" tutorial, Dr. AIST Toshihiro kamishima, Japan

Advanced learning of MySQL -- Application -- index

長文綜述:大腦中的熵、自由能、對稱性和動力學

Dare to climb here, you're not far from prison, reptile reverse actual combat case

7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages

Save Private Ryan - map building + voltage dp+deque+ shortest circuit

Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami
随机推荐
Contest3145 - the 37th game of 2021 freshman individual training match_ D: Ranking
C learning notes: C foundation - Language & characteristics interpretation
I stepped on a foundation pit today
Talking about custom conditions and handling errors in MySQL Foundation
Yyds dry goods inventory hand-in-hand teach you the development of Tiktok series video batch Downloader
Redis transaction
Final consistency of MESI cache in CPU -- why does CPU need cache
Problems and solutions of several concurrent scenarios of redis
The "two-way link" of pushing messages helps app quickly realize two-way communication capability
[Yugong series] February 2022 attack and defense world advanced question misc-84 (MySQL)
Love and self-discipline and strive to live a core life
[untitled]
Dans la recherche de l'intelligence humaine ai, Meta a misé sur l'apprentissage auto - supervisé
CSCI 2134
I stepped on a foundation pit today
Contest3145 - the 37th game of 2021 freshman individual training match_ J: Eat radish
Gee import SHP data - crop image
Setting methods, usage methods and common usage scenarios of environment variables in postman
Ai aide à la recherche de plagiat dans le design artistique! L'équipe du professeur Liu Fang a été embauchée par ACM mm, une conférence multimédia de haut niveau.
There is no need to authorize the automatic dream weaving collection plug-in for dream weaving collection