<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
C# 利用websocket實現簡易聊天功能——伺服器端,供大家參考,具體內容如下
介面設計程式碼
namespace chat_server { partial class Form1 { /// <summary> /// 必需的設計器變數。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的資源。 /// </summary> /// <param name="disposing">如果應釋放託管資源,為 true;否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 表單設計器生成的程式碼 /// <summary> /// 設計器支援所需的方法 - 不要修改 /// 使用程式碼編輯器修改此方法的內容。 /// </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 = "開啟服務"; 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 = "傳送"; 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 = "伺服器"; 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、建立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、開啟監聽 socket.Listen(10);//等待連線佇列的最大值 //4、開始接受使用者端的連結 ThreadPool.QueueUserWorkItem(new WaitCallback(connect), socket); } catch { MessageBox.Show("啟動伺服器失敗"); } } private void connect(object socket) { var serverSockert = socket as Socket;//強制轉換 showLog("伺服器正常啟動,開始接受使用者端的資料"); 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} 連線伺服器", proxSocket.RemoteEndPoint.ToString(),name)); String msg = String.Format("使用者{0}上線了", name); sendMsg(msg); userContain[proxSocket] = name;//把物件放入集合中 //不停的接受當前連結的使用者端傳送的訊息 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];//接受,傳送資料緩衝區 String msg; int len = 0; // 資料長度 String name = userContain[proxSocket]; // 使用者端名字 while (true) { try { len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None); } catch { msg = String.Format("使用者端{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("使用者端{0}正常退出", proxSocket.RemoteEndPoint.ToString()); showLog(msg); msg = String.Format("使用者{0}下線了", name); sendMsg(msg); userContain.Remove(proxSocket); stopConnect(proxSocket); return;//結束當前接受使用者端資料的非同步執行緒 } //接受訊息 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+"rn"; }),msg); } else { this.textBoxLog.Text += msg; } } private void buttonSend_Click(object sender, EventArgs e) { //傳送訊息 String msg = String.Format("伺服器釋出通知資訊{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); } } } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援it145.com。
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45