C#基于Socket實(shí)現(xiàn)多人聊天功能
本文實(shí)例為大家分享了C#基于Socket實(shí)現(xiàn)多人聊天功能的具體代碼,供大家參考,具體內(nèi)容如下
服務(wù)器
服務(wù)器負(fù)責(zé)接受所有客戶端發(fā)來的消息,和將接受到的問題群發(fā)到其他用戶。
代碼:
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatRoomService { ? ? class Service ? ? { ? ? ? ? Socket socketSevice ; ? ? ? ? List<Socket> userList;//用戶組 ? ? ? ? public Service() ? ? ? ? { ? ? ? ? ? ?socketSevice = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ? ? ? ? ? ?userList = new List<Socket>(); ? ? ? ? } ? ? ? ? public void ?Start() ? ? ? ? { ? ? ? ? ? ? socketSevice.Bind(new IPEndPoint(IPAddress.Any,5566)); ? ? ? ? ? ? socketSevice.Listen(10); ? ? ? ? ? ? Console.WriteLine("服務(wù)器啟動成功"); ? ? ? ? ? ? //開啟接受連接,用多線程 ? ? ? ? ? ? Thread accThread = new Thread(Accept); ? ? ? ? ? ? accThread.IsBackground = true; ? ? ? ? ? ? accThread.Start(); ? ? ? ? } ? ? ? ? private void Accept() ? ? ? ? { ? ? ? ? ? ? //接受連接 ? ? ? ? ? ? Socket clientSocket = socketSevice.Accept(); ? ? ? ? ? ? userList.Add(clientSocket); ? ? ? ? ? ? //打印已經(jīng)連接IP地址 ? ? ? ? ? ? Console.WriteLine(IPToAddress(clientSocket)+"連接進(jìn)來了"); ? ? ? ? ? ? // ? ? ? ? ? ? Thread RecvThread = new Thread(ReceMessage); ? ? ? ? ? ? RecvThread.IsBackground = true; ? ? ? ? ? ? RecvThread.Start(clientSocket); ? ? ? ? ? ? Accept();//遞歸 ? ? ? ? } ? ? ? ? //接收客戶端信息 ? ? ? ? private void ReceMessage(Object obj) ? ? ? ? { ? ? ? ? ? ? Socket client = obj as Socket; ? ? ? ? ? ? byte[] strByte = new byte[1024 * 1024];//設(shè)定接受字符的長度 ? ? ? ? ? ? string str = ""; ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? int len = client.Receive(strByte);//接受用戶發(fā)送的內(nèi)容 ? ? ? ? ? ? ? str = Encoding.Default.GetString(strByte, 0, len); ? ? ? ? ? ? ? Broadcast(str,client);//廣播給用戶 ? ? ? ? ? ? ? Console.WriteLine(str); ? ? ? ? ? ? ?} ? ? ? ? ? ? ?catch (Exception e) ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? Console.WriteLine(IPToAddress(client)+"退出"); ? ? ? ? ? ? ? ? userList.Remove(client); ? ? ? ? ? ? ? ? Thread.CurrentThread.Abort();//退出時(shí)掐死線程,不然遞歸反彈 ? ? ? ? ? ? } ? ? ? ? ? ?ReceMessage(client); //使用遞歸 ? ? ? ? } ? ? ? ? /// <summary> ? ? ? ? /// 廣播信息 ? ? ? ? /// </summary> ? ? ? ? /// <param name="useStr">傳入收到的傳輸?shù)膬?nèi)容</param> ? ? ? ? /// <param name="obj">傳送信息的客戶</param> ? ? ? ? private void Broadcast(string userStr,object obj) ? ? ? ? { ? ? ? ? ? ? Socket clientSend = obj as Socket; //當(dāng)前發(fā)送信息的客戶 ? ? ? ? ? ? foreach (Socket client in userList) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? if (client != clientSend)//將信息廣播給其他用戶 ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? client.Send(Encoding.Default.GetBytes(IPToAddress(clientSend)+":"+userStr)); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? }? ? ? ? //轉(zhuǎn)換出連來客戶的IP地址 ? ? ? ? private string IPToAddress(Socket soket) ? ? ? ? { ? ? ? ? ? ? return (soket.RemoteEndPoint as IPEndPoint).Address.ToString(); ? ? ? ? } ? ? } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChatRoomService { ? ? class Program ? ? { ? ? ? ? static void Main(string[] args) ? ? ? ? { ? ? ? ? ? ? Service ss = new Service(); ? ? ? ? ? ? ss.Start(); ? ? ? ? ? ? Console.ReadLine(); ? ? ? ? } ? ? } }
客戶端
客戶端的功能開始十分簡單,可以發(fā)送信息給服務(wù)器。也可以接收服務(wù)器轉(zhuǎn)發(fā)過來其他客戶端的信息。
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ChatRoom { ? ? class ClientRoom ? ? { ? ? ? ? Socket clientSocket; ? ? ? ? public ClientRoom() ? ? ? ? { ? ? ? ? ? ? clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化服務(wù)器 ? ? ? ? } ? ? ? ? /// <summary> ? ? ? ? /// 連接服務(wù)器 ? ? ? ? /// </summary> ? ? ? ? /// <param name="Ip"></param> ? ? ? ? /// <param name="port"></param> ? ? ? ? public void Connected(string Ip,int port) ? ? ? ? { ? ? ? ? ? ? clientSocket.Connect(Ip,port); ? ? ? ? ? ? Console.WriteLine("連接成功"); ? ? ? ? ? ? // ClientSocket.Bind(new IPEndPoint()); ? ? ? ? ? ? Thread RecvThread = new Thread(RecvMessage); ? ? ? ? ? ? RecvThread.IsBackground = true; ? ? ? ? ? ? RecvThread.Start(); ? ? ? ? } ? ? ? ?public void Send(String str) ? ? ? ? { ? ? ? ? ? ? clientSocket.Send(Encoding.Default.GetBytes(str)); ? ? ? ? } ? ? ? ? /// <summary> ? ? ? ? /// 接受信息 ? ? ? ? /// </summary> ? ? ? ? private void RecvMessage() ? ? ? ? { ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? byte[] strByte = new byte[500 * 1024]; ? ? ? ? ? ? ? ? int len = clientSocket.Receive(strByte); ? ? ? ? ? ? ? ? Console.WriteLine(Encoding.Default.GetString(strByte, 0, len)); ? ? ? ? ? ? } ? ? ? ? ? ? catch (Exception e) //服務(wù)器關(guān)閉 ? ? ? ? ? ? { ? ? ? ? ? ? ? ? Console.WriteLine("服務(wù)器關(guān)閉"); ? ? ? ? ? ? ? ? Thread.CurrentThread.Abort();//關(guān)閉時(shí)切斷進(jìn)程 ? ? ? ? ? ? } ? ? ? ? ? ? RecvMessage(); ? ? ? ? } ? ? ? ? ? ? } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChatRoom { ? ? class Program ? ? { ? ? ? ? static void Main(string[] args) ? ? ? ? { ? ? ? ? ? ? ClientRoom client = new ClientRoom(); ? ? ? ? ? ? client.Connected("127.0.0.1", 5566); ? ? ? ? ? ? string str = Console.ReadLine(); ? ? ? ? ? ? while (!str.Equals("q")) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? client.Send(str); ? ? ? ? ? ? ? ? str = Console.ReadLine(); ? ? ? ? ? ? } ? ? ? ? ? ? Console.ReadLine(); ? ? ? ? } ? ? } }
可以正常對話,測試一下。假裝和自己對話
目前還沒有解決沾包問題
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用aspose.word 第三方的插件實(shí)現(xiàn)導(dǎo)出word
本文給大家分享的是一個(gè)使用使用aspose.word 第三方的插件實(shí)現(xiàn)導(dǎo)出word的實(shí)例,十分的實(shí)用,有需要的小伙伴可以參考下。2015-06-06c#開發(fā)的程序安裝時(shí)動態(tài)指定windows服務(wù)名稱
前段時(shí)間由于項(xiàng)目的需求,要在Windows里把同樣的組件制作成多個(gè)不同名稱的服務(wù),這些服務(wù)完成類似的功能,僅需要修改業(yè)務(wù)配置文件2012-06-06C#異步綁定數(shù)據(jù)實(shí)現(xiàn)方法
這篇文章主要介紹了C#異步綁定數(shù)據(jù)實(shí)現(xiàn)方法,實(shí)例分析了C#操作數(shù)據(jù)庫及異步綁定的相關(guān)實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09c#橋接模式(bridge結(jié)構(gòu)模式)用法實(shí)例
這篇文章主要介紹了c#橋接模式(bridge結(jié)構(gòu)模式)用法,較為詳細(xì)的分析了橋接模式的原理與用法實(shí)例,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2014-12-12unity實(shí)現(xiàn)車方向盤轉(zhuǎn)動效果
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)車方向盤轉(zhuǎn)動效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04