c#實(shí)現(xiàn)多線程局域網(wǎng)聊天系統(tǒng)
覺(jué)得好有點(diǎn)幫助就頂一下啦。
socke編程,支持多客戶端,多線程操作避免界面卡死。
開(kāi)啟socket
private void button1_Click(object sender, EventArgs e) { try { int port = int.Parse(txt_port.Text); string host = txt_ip.Text; //創(chuàng)建終結(jié)點(diǎn) IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); //創(chuàng)建Socket并開(kāi)始監(jiān)聽(tīng) newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //創(chuàng)建一個(gè)Socket對(duì)象,如果用UDP協(xié)議,則要用SocketTyype.Dgram類型的套接字 newsock.Bind(ipe); //綁定EndPoint對(duì)象 newsock.Listen(0); //開(kāi)始監(jiān)聽(tīng) //為新建立的連接創(chuàng)建新的Socket acceptClientThread = new Thread(new ThreadStart(AcceptClient)); acceptClientThread.Start(); SetText("開(kāi)始監(jiān)聽(tīng)"); } catch (Exception exp) { CommonFunction.WriteLog(exp, exp.Message); } }
監(jiān)控端口,接收客戶端
/// <summary> /// 接受客戶端,可接受多個(gè)客戶端同時(shí)連入,并對(duì)連入的客戶端注冊(cè)到客戶端列表 /// </summary> public void AcceptClient() { try { while (true) { Socket client = newsock.Accept(); ip = client.Handle; RegeistUser(client.Handle, client); Thread clientThread = new Thread(new ParameterizedThreadStart(ReceiveData)); object o = client; clientThread.Start(o); } } catch (Exception exp) { CommonFunction.WriteLog(exp, exp.Message); } }
接收客戶端數(shù)據(jù)并廣播數(shù)據(jù)
/// <summary> /// 接收客戶端數(shù)據(jù)并,轉(zhuǎn)發(fā)到目標(biāo)客戶端。 /// </summary> public void ReceiveData(object o) { try { while (true) { Socket client = (Socket)o; string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = client.Receive(recvBytes, recvBytes.Length, 0); //從客戶端接受消息 recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes); SendMessage(client, recvStr); SetText(recvStr); CommonFunction.WriteErrorLog(recvStr); } } catch (Exception exp) { CommonFunction.WriteLog(exp, exp.Message); } }
判斷是用戶注冊(cè)還是發(fā)送消息
/// <summary> /// 判斷是用戶注冊(cè)還是發(fā)送消息 /// </summary> /// <param name="p_strMessage"></param> public void SendMessage(Socket client,string p_strMessage) { if (p_strMessage.StartsWith("@")) { RegeistUser(p_strMessage, client); } else if (p_strMessage.StartsWith(">")) { DeleteClident(p_strMessage); } else { //SendMessageToTarget(p_strMessage); SendAllMessage(p_strMessage); } }
將socket注冊(cè)為指定用戶名
/// <summary> /// 將socket注冊(cè)為指定用戶名 /// </summary> /// <param name="user"></param> /// <param name="ss"></param> public void RegeistUser(string user, Socket ss) { user = user.Remove(0, 1); userSocketDict.Add(user, ss); SendOneMessage(ss, "歡迎" + user + "連入!"); RefreshClient(); }
從客戶端字典中移除客戶端
/// <summary> /// 從客戶端字典中移除客戶端 /// </summary> /// <param name="p_strMessage"></param> public void DeleteClident(string p_strMessage) { p_strMessage = p_strMessage.Remove(0, 1); userSocketDict.Remove(p_strMessage); RefreshClient(); }
群發(fā)消息
/// <summary> /// 群發(fā)消息 /// </summary> /// <param name="p_strsend"></param> public void SendAllMessage(string p_strsend) { //MessageBox.Show(p_strsend); foreach (string item in userSocketDict.Keys) { byte[] bs = Encoding.UTF8.GetBytes(p_strsend); userSocketDict[item].Send(bs, bs.Length, 0); } }
給文本框賦值
public delegate void SetTextHandler(string text); /// <summary> /// 給文本框賦值 /// </summary> /// <param name="text"></param> private void SetText(string text) { if (rich_back.InvokeRequired == true) { SetTextHandler set = new SetTextHandler(SetText);//委托的方法參數(shù)應(yīng)和SetText一致 rich_back.Invoke(set, new object[] { text }); //此方法第二參數(shù)用于傳入方法,代替形參text } else { rich_back.Text += "\n" + text; } }
連入服務(wù)器
private void button1_Click(object sender, EventArgs e) { try { user = txt_name.Text; int port = int.Parse(txt_port.Text); string host = txt_ip.Text; //創(chuàng)建終結(jié)點(diǎn)EndPoint IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); //把ip和端口轉(zhuǎn)化為IPEndPoint的實(shí)例 //創(chuàng)建Socket并連接到服務(wù)器 Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 創(chuàng)建Socket cc = c; c.Connect(ipe); //連接到服務(wù)器 clientThread = new Thread(new ThreadStart(ReceiveData)); clientThread.Start(); //向服務(wù)器發(fā)送本機(jī)用戶名,以便服務(wù)器注冊(cè)客戶端 SendMessage("@" + txt_name.Text); } catch (ArgumentException ex) { Console.WriteLine("argumentNullException:{0}", ex); } catch (SocketException exp) { Console.WriteLine("SocketException:{0}",exp); } }
向服務(wù)器發(fā)送消息
private void button3_Click(object sender, EventArgs e) { if (""==txt_target.Text) { MessageBox.Show("未選擇對(duì)話人物"); return; } //向服務(wù)器發(fā)送信息 string sendStr = txt_name.Text + "@" + target + ":" + txt_message.Text; SendMessage(sendStr); rch_back.Text += "\n" + sendStr; txt_message.Text = ""; }
隱身
private void button2_Click(object sender, EventArgs e) { try { SendMessage(">" + txt_name.Text); //cc.Disconnect(true); //cc.Shutdown(SocketShutdown.Both); //cc.Close(); } catch (Exception exp) { CommonFunction.WriteLog(exp, exp.Message); } }
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。
- 分享一個(gè)C#編寫(xiě)簡(jiǎn)單的聊天程序(詳細(xì)介紹)
- C#制作簡(jiǎn)單的多人在線即時(shí)交流聊天室
- C#聊天程序服務(wù)端與客戶端完整實(shí)例代碼
- 基于c#用Socket做一個(gè)局域網(wǎng)聊天工具
- c#多線程網(wǎng)絡(luò)聊天程序代碼分享(服務(wù)器端和客戶端)
- C#實(shí)現(xiàn)簡(jiǎn)單聊天程序的方法
- C#使用Socket實(shí)現(xiàn)局域網(wǎng)聊天
- C#基于UDP實(shí)現(xiàn)的P2P語(yǔ)音聊天工具
- C#使用Socket實(shí)現(xiàn)服務(wù)器與多個(gè)客戶端通信(簡(jiǎn)單的聊天系統(tǒng))
- C#實(shí)現(xiàn)簡(jiǎn)單的聊天窗體
相關(guān)文章
淺析C# web訪問(wèn)mysql數(shù)據(jù)庫(kù)-整理歸納總結(jié)
本篇文章是對(duì)C#中的web訪問(wèn)mysql數(shù)據(jù)庫(kù)的一些知識(shí)點(diǎn)進(jìn)行了整理歸納總結(jié),需要的朋友可以參考下2013-07-07聊聊C# 中HashTable與Dictionary的區(qū)別說(shuō)明
這篇文章主要介紹了聊聊C# 中HashTable與Dictionary的區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01C# 從Excel讀取數(shù)據(jù)向SQL server寫(xiě)入
這篇文章主要介紹了C# 從Excel讀取數(shù)據(jù)向SQL server寫(xiě)入的方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03c#實(shí)現(xiàn)用SQL池,多線程定時(shí)批量執(zhí)行SQL語(yǔ)句的方法
構(gòu)建SQL池,分離業(yè)務(wù)邏輯層和數(shù)據(jù)訪問(wèn)層,讓業(yè)務(wù)邏輯層從低效的數(shù)據(jù)庫(kù)操作解脫,以提高系統(tǒng)整體性能2013-10-10C#測(cè)量程序運(yùn)行時(shí)間及cpu使用時(shí)間實(shí)例方法
對(duì)一個(gè)服務(wù)器程序想統(tǒng)計(jì)每秒可以處理多少數(shù)據(jù)包,要如何做?答案是用處理數(shù)據(jù)包的總數(shù),除以累記處理數(shù)據(jù)包用的時(shí)間,下面我們看一個(gè)代碼實(shí)例就明白了2013-11-11C#創(chuàng)建windows系統(tǒng)用戶的方法
這篇文章主要介紹了C#創(chuàng)建windows系統(tǒng)用戶的方法,涉及C#操作用戶名、密碼、顯示名稱、描述、是否強(qiáng)制修改密碼、密碼是否過(guò)期等技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04C#使用NPOI實(shí)現(xiàn)Excel和DataTable的互轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了C#使用NPOI實(shí)現(xiàn)Excel和DataTable的互轉(zhuǎn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02