您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關怎么在C#中使用Socket實現局域網聊天,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
先運行一個java寫的局域網聊天,效果圖如下
后使用c#圖形修改如下:
C#代碼:
servlet服務端
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace Server { public partial class MainForm : Form { private TcpListener listener; private Dictionary<String,TcpClient> socketList; private bool tag = true; private StringBuilder charList; public MainForm() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } void Bu_StartClick(object sender, EventArgs e) { cb_chatList.Items.Clear(); selectChat.Text=""; int port = 8888; //創建服務端,并且啟動 try{ listener = new TcpListener(IPAddress.Parse(ipAddress()),port); listener.Start(); bu_Start.Enabled = false; bu_stop.Enabled = true; }catch(Exception ex) { MessageBox.Show("服務器啟動失敗, 原因:"+ex.Message); bu_Start.Enabled = true; bu_stop.Enabled = false; return; } selectChat.Text = "服務器啟動成功,訪問IP:"+ipAddress()+" 端口號:"+port; //記錄住連接的客戶端 socketList = new Dictionary<String,TcpClient>(); charList = new StringBuilder(); //使用多線程,用于多個客戶端接入 Thread th = new Thread(new ThreadStart(executeTask)); th.Start(); } public void executeTask() { while(tag) { //等待用戶連接 TcpClient client = null; try{ client = listener.AcceptTcpClient(); }catch(Exception) { } Thread th = new Thread(executeRead); th.Start((Object)client); } } public void executeRead(Object pamars) { //永久監聽讀取客戶端 TcpClient client = pamars as TcpClient; while(tag) { NetworkStream ns = client.GetStream(); StreamReader sr = new StreamReader(ns); String msg = String.Empty; String people = String.Empty; try { msg = sr.ReadLine(); if(msg.IndexOf("<clientName>")!=-1) { msg = Regex.Split(msg,"=")[1]; cb_chatList.Items.Add(msg); charList.Append(msg).Append("<@>"); socketList.Add(msg,client); msg = "<br>歡迎【"+msg+"】光臨<br>"; } selectChat.AppendText(msg.Replace("<br>","\r\n")); sendMsg(String.Empty,msg); } catch (Exception) { //MessageBox.Show(ex.Message.ToString()); break; } } } public void sendMsg(String target,String msg) { if(String.Empty!=target) { TcpClient client = socketList[target]; StreamWriter sw = new StreamWriter(client.GetStream()); sw.WriteLine(msg); sw.Flush(); }else{ Dictionary<String,TcpClient>.KeyCollection keyColl = socketList.Keys; foreach (String name in keyColl) { StreamWriter sw = new StreamWriter(socketList[name].GetStream()); sw.WriteLine(msg+"<@=@>"+charList.ToString()); sw.Flush(); } } } /*根據計算名獲取IP地址*/ public String ipAddress() { IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName()); return address[2].ToString(); } void ServerFromFormClosing(object sender, FormClosingEventArgs e) { e.Cancel = false; if(tag) tag = false; if(listener!=null) listener.Stop(); } void Bu_stopClick(object sender, EventArgs e) { bu_Start.Enabled = true; bu_stop.Enabled = false; if(tag) tag = false; if(listener!=null) listener.Stop(); } } }
Client客戶端
using System; using System.Drawing; using System.Windows.Forms; using System.Threading; using System.Net; using System.Net.Sockets; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace Client { public partial class MainForm : Form { private System.Windows.Forms.Timer closeWindowTimer; private StreamReader sr; private StreamWriter sw; private TcpClient tc; private ClientLong cl; private bool tag = true; public MainForm(TcpClient tcp,ClientLong clo) { cl = clo; tc = tcp; InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; bu_simple.Hide(); } void ClientFromLoad(object sender, EventArgs e) { PiayCheckedChanged(); } /*事件方法*/ public void PiayCheckedChanged() { closeWindowTimer = new System.Windows.Forms.Timer(); closeWindowTimer.Interval = 1000; closeWindowTimer.Tick += new EventHandler(theout); closeWindowTimer.Start(); } /*執行的事件*/ public void theout(object source, EventArgs e) { //這里單獨開一個線程用來顯示信息 try{ Thread t1 = new Thread(new ThreadStart(readMsg)); t1.Start(); }catch(Exception) { } } void readMsg() { if(tag && tc!=null){ sr = new StreamReader(tc.GetStream()); String msg = sr.ReadLine(); String[] address = Regex.Split(msg,"<@=@>"); chatText.AppendText(address[0].Replace("<br>","\r\n")); address = Regex.Split(address[1],"<@>"); cb_chatList.Items.Clear(); foreach (String s in address) { if(!String.IsNullOrEmpty(s) && s != cl.clientName) cb_chatList.Items.Add(s); } } } void Button1Click(object sender, EventArgs e) { if(String.IsNullOrEmpty(textBox2.Text)){ MessageBox.Show("請輸入消息");return; } sw = new StreamWriter(tc.GetStream()); sw.WriteLine("<br>"+cl.clientName+" "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"<br> "+textBox2.Text); textBox2.Text = ""; sw.Flush(); } void Bu_exitClick(object sender, EventArgs e) { MainFormFormClosing(null,null); } void Button2Click(object sender, EventArgs e) { chatText.Text = ""; } void MainFormFormClosing(object sender, FormClosingEventArgs e) { closeWindowTimer.Stop(); cl.Close(); tag = false; if(sr!=null) sr.Close(); if(sw!=null) sw.Close(); } void Bu_simpleClick(object sender, EventArgs e) { String selected = cb_chatList.Text; if(selected==null) { MessageBox.Show("請選擇單聊對象"); return; } } } }
C#是一個簡單、通用、面向對象的編程語言,它由微軟Microsoft開發,繼承了C和C++強大功能,并且去掉了一些它們的復雜特性,C#綜合了VB簡單的可視化操作和C++的高運行效率,以其強大的操作能力、優雅的語法風格、創新的語言特性和便捷的面向組件編程從而成為.NET開發的首選語言,但它不適用于編寫時間急迫或性能非常高的代碼,因為C#缺乏性能極高的應用程序所需要的關鍵功能。
關于怎么在C#中使用Socket實現局域網聊天就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。