当前位置:网站首页>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 !
边栏推荐
- Résumé des outils communs et des points techniques de l'examen PMP
- Servlet simple verification code generation
- Remote work guide
- [UE4] parse JSON string
- Jenkins continuous integration environment construction V (Jenkins common construction triggers)
- Keepalived set the master not to recapture the VIP after fault recovery (it is invalid to solve nopreempt)
- 中電資訊-信貸業務數字化轉型如何從星空到指尖?
- Experience summary of the 12th Blue Bridge Cup (written for the first time)
- Unity controls the selection of the previous and next characters
- Li Chuang EDA learning notes IX: layers
猜你喜欢

FRP intranet penetration

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.

High level application of SQL statements in MySQL database (I)

Bugku Zhi, you have to stop him

Jenkins continuous integration environment construction V (Jenkins common construction triggers)

LV1 previous life archives

Introduction to graphics: graphic painting (I)

Li Chuang EDA learning notes IX: layers

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

Kiss number + close contact problem
随机推荐
Gee import SHP data - crop image
Jenkins continuous integration environment construction V (Jenkins common construction triggers)
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.
查詢效率提昇10倍!3種優化方案,幫你解决MySQL深分頁問題
Yyds dry goods inventory override and virtual of classes in C
The 37 year old programmer was laid off, and he didn't find a job for 120 days. He had no choice but to go to a small company. As a result, he was confused
15. System limitations and options
基於.NetCore開發博客項目 StarBlog - (14) 實現主題切換功能
Career development direction
60 year old people buy medical insurance and recommend a better product
Pagoda SSL can't be accessed? 443 port occupied? resolvent
Yyds dry goods inventory hand-in-hand teach you the development of Tiktok series video batch Downloader
Global and Chinese market of contour projectors 2022-2028: Research Report on technology, participants, trends, market size and share
What is the intelligent monitoring system of sewage lifting pump station and does it play a big role
Contest3145 - the 37th game of 2021 freshman individual training match_ F: Smallest ball
Create real-time video chat in unity3d
Final consistency of MESI cache in CPU -- why does CPU need cache
The automatic control system of pump station has powerful functions and diverse application scenarios
Résumé: entropie, énergie libre, symétrie et dynamique dans le cerveau
Mysql to PostgreSQL real-time data synchronization practice sharing