C#用websocket實現(xiàn)簡易聊天功能(服務(wù)端)
更新時間:2022年02月11日 15:01:09 作者:antRain
這篇文章主要為大家詳細(xì)介紹了C#用websocket實現(xiàn)簡易聊天功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
C# 利用websocket實現(xiàn)簡易聊天功能——服務(wù)端,供大家參考,具體內(nèi)容如下
前言
- 使用C#語言進(jìn)行開發(fā),基于.NET FrameWork4
- 功能包含群聊,和私聊
界面
界面設(shè)計代碼
namespace chat_server { ? ? partial class Form1 ? ? { ? ? ? ? /// <summary> ? ? ? ? /// 必需的設(shè)計器變量。 ? ? ? ? /// </summary> ? ? ? ? private System.ComponentModel.IContainer components = null; ? ? ? ? /// <summary> ? ? ? ? /// 清理所有正在使用的資源。 ? ? ? ? /// </summary> ? ? ? ? /// <param name="disposing">如果應(yīng)釋放托管資源,為 true;否則為 false。</param> ? ? ? ? protected override void Dispose(bool disposing) ? ? ? ? { ? ? ? ? ? ? if (disposing && (components != null)) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? components.Dispose(); ? ? ? ? ? ? } ? ? ? ? ? ? base.Dispose(disposing); ? ? ? ? } ? ? ? ? #region Windows 窗體設(shè)計器生成的代碼 ? ? ? ? /// <summary> ? ? ? ? /// 設(shè)計器支持所需的方法 - 不要修改 ? ? ? ? /// 使用代碼編輯器修改此方法的內(nèi)容。 ? ? ? ? /// </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 = "開啟服務(wù)"; ? ? ? ? ? ? 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 = "發(fā)送"; ? ? ? ? ? ? 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 = "服務(wù)器"; ? ? ? ? ? ? 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; ? ? } }
源代碼
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連接容器 ? ? ? ? Dictionary<Socket, String> userContain = new Dictionary<Socket, string>(); ? ? ? ?? ? ? ? ? private void buttonStart_Click(object sender, EventArgs e) ? ? ? ? { ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? //1、創(chuàng)建socket ? ? ? ? ? ? ? ? Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ? ? ? ? ? ? ? ? //2、綁定ip和端口 ? ? ? ? ? ? ? ? String ip = textBoxIP.Text; ? ? ? ? ? ? ? ? int port = Convert.ToInt32(textBoxPort.Text); ? ? ? ? ? ? ? ? socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); ? ? ? ? ? ? ? ? //3、開啟監(jiān)聽 ? ? ? ? ? ? ? ? socket.Listen(10);//等待連接隊列的最大值 ? ? ? ? ? ? ? ? //4、開始接受客戶端的鏈接 ? ? ? ? ? ? ? ? ThreadPool.QueueUserWorkItem(new WaitCallback(connect), socket); ? ? ? ? ? ? } ? ? ? ? ? ? catch ? ? ? ? ? ? { ? ? ? ? ? ? ? ? MessageBox.Show("啟動服務(wù)器失敗"); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ?? ? ? ? ? private void connect(object socket) ? ? ? ? { ? ? ? ? ? ? var serverSockert = socket as Socket;//強制轉(zhuǎn)換 ? ? ? ? ? ? showLog("服務(wù)器正常啟動,開始接受客戶端的數(shù)據(jù)"); ? ? ? ? ? ? byte[] data = new byte[1024]; ? ? ? ? ? ? int len; ? ? ? ? ? ? String name; //客戶端的用戶名 ? ? ? ? ? ? while (true) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? try ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? var proxSocket = serverSockert.Accept();//接受連接 ? ? ? ? ? ? ? ? ? ? len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);//接受客戶端的用戶名 ? ? ? ? ? ? ? ? ? ? name = Encoding.Default.GetString(data, 0, len); ? ? ? ? ? ? ? ? ? ? showLog(String.Format("客戶端 {0} 用戶名 {1} 連接服務(wù)器", proxSocket.RemoteEndPoint.ToString(),name)); ? ? ? ? ? ? ? ? ? ? String msg = String.Format("用戶{0}上線了", name); ? ? ? ? ? ? ? ? ? ? sendMsg(msg); ? ? ? ? ? ? ? ? ? ? userContain[proxSocket] = name;//把對象放入集合中 ? ? ? ? ? ? ? ? ? ? //不停的接受當(dāng)前鏈接的客戶端發(fā)送的消息 ? ? ? ? ? ? ? ? ? ? ThreadPool.QueueUserWorkItem(new WaitCallback(this.recevie), proxSocket); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? catch ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? MessageBox.Show("接受異常"); ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? private void recevie(object socket) ? ? ? ? { ? ? ? ? ? ? var proxSocket = socket as Socket; ? ? ? ? ? ? byte[] data = new byte[1024 * 1024];//接受,發(fā)送數(shù)據(jù)緩沖區(qū) ? ? ? ? ? ? String msg; ? ? ? ? ? ? int len = 0; // 數(shù)據(jù)長度 ? ? ? ? ? ? String name = userContain[proxSocket]; // 客戶端名字 ? ? ? ? ? ? while (true) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? try ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? catch ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? msg = String.Format("客戶端{(lán)0}異常退出", ? ? ? ? ? ? ? ? ? ? proxSocket.RemoteEndPoint.ToString()); ? ? ? ? ? ? ? ? ? ? showLog(msg); ? ? ? ? ? ? ? ? ? ? msg = String.Format("用戶{0}下線了", name); ? ? ? ? ? ? ? ? ? ? sendMsg(msg); ? ? ? ? ? ? ? ? ? ? userContain.Remove(proxSocket); ? ? ? ? ? ? ? ? ? ? stopConnect(proxSocket); ? ? ? ? ? ? ? ? ? ? return; ? ? ? ? ? ? ? ? } ? ? ? ? ?? ? ? ? ? ? ? ? ? if (len <= 0) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? //客戶端正常退出 ? ? ? ? ? ? ? ? ? ? msg = String.Format("客戶端{(lán)0}正常退出", ? ? ? ? ? ? ? ? ? ? proxSocket.RemoteEndPoint.ToString()); ? ? ? ? ? ? ? ? ? ? showLog(msg); ? ? ? ? ? ? ? ? ? ? msg = String.Format("用戶{0}下線了", name); ? ? ? ? ? ? ? ? ? ? sendMsg(msg); ? ? ? ? ? ? ? ? ? ? userContain.Remove(proxSocket); ? ? ? ? ? ? ? ? ? ? stopConnect(proxSocket); ? ? ? ? ? ? ? ? ? ? return;//結(jié)束當(dāng)前接受客戶端數(shù)據(jù)的異步線程 ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? //接受消息 ? ? ? ? ? ? ? ? msg = Encoding.Default.GetString(data, 0, len); ? ? ? ? ? ? ? ? //私聊信息格式@name:msg ? ? ? ? ? ? ? ? //name 為用戶名 msg 為消息 ? ? ? ? ? ? ? ? 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("用戶{0} 單獨對你說:{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("用戶{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) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? //如果是跨線程訪問 ? ? ? ? ? ? ? ? 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) ? ? ? ? { ? ? ? ? ? ? //發(fā)送消息 ? ? ? ? ? ? String msg = String.Format("服務(wù)器發(fā)布通知信息{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); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ? } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用C#/VB.NET實現(xiàn)將PDF轉(zhuǎn)為Word
眾所周知,PDF 文檔支持特長文件,集成度和安全可靠性都較高,可有效防止他人對 PDF 內(nèi)容進(jìn)行更改,所以在工作中深受大家喜愛。本文將分為兩部分介紹如何以編程的方式將 PDF 轉(zhuǎn)換為 Word,需要的可以參考一下2022-12-12C# Color.FromArgb()及系統(tǒng)顏色對照表一覽
這篇文章主要介紹了C# Color.FromArgb()及系統(tǒng)顏色對照表一覽,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01C#對多個集合和數(shù)組的操作方法(合并,去重,判斷)
下面小編就為大家?guī)硪黄狢#對多個集合和數(shù)組的操作方法(合并,去重,判斷)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12