網站首頁 編程語言 正文
本文實例為大家分享了C#基于Socket實現多人聊天功能的具體代碼,供大家參考,具體內容如下
服務器
服務器負責接受所有客戶端發(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("服務器啟動成功"); ? ? ? ? ? ? //開啟接受連接,用多線程 ? ? ? ? ? ? Thread accThread = new Thread(Accept); ? ? ? ? ? ? accThread.IsBackground = true; ? ? ? ? ? ? accThread.Start(); ? ? ? ? } ? ? ? ? private void Accept() ? ? ? ? { ? ? ? ? ? ? //接受連接 ? ? ? ? ? ? Socket clientSocket = socketSevice.Accept(); ? ? ? ? ? ? userList.Add(clientSocket); ? ? ? ? ? ? //打印已經連接IP地址 ? ? ? ? ? ? Console.WriteLine(IPToAddress(clientSocket)+"連接進來了"); ? ? ? ? ? ? // ? ? ? ? ? ? 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];//設定接受字符的長度 ? ? ? ? ? ? string str = ""; ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? int len = client.Receive(strByte);//接受用戶發(fā)送的內容 ? ? ? ? ? ? ? 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();//退出時掐死線程,不然遞歸反彈 ? ? ? ? ? ? } ? ? ? ? ? ?ReceMessage(client); //使用遞歸 ? ? ? ? } ? ? ? ? /// <summary> ? ? ? ? /// 廣播信息 ? ? ? ? /// </summary> ? ? ? ? /// <param name="useStr">傳入收到的傳輸的內容</param> ? ? ? ? /// <param name="obj">傳送信息的客戶</param> ? ? ? ? private void Broadcast(string userStr,object obj) ? ? ? ? { ? ? ? ? ? ? Socket clientSend = obj as Socket; //當前發(fā)送信息的客戶 ? ? ? ? ? ? foreach (Socket client in userList) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? if (client != clientSend)//將信息廣播給其他用戶 ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? client.Send(Encoding.Default.GetBytes(IPToAddress(clientSend)+":"+userStr)); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? }? ? ? ? //轉換出連來客戶的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ā)送信息給服務器。也可以接收服務器轉發(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);//初始化服務器 ? ? ? ? } ? ? ? ? /// <summary> ? ? ? ? /// 連接服務器 ? ? ? ? /// </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) //服務器關閉 ? ? ? ? ? ? { ? ? ? ? ? ? ? ? Console.WriteLine("服務器關閉"); ? ? ? ? ? ? ? ? Thread.CurrentThread.Abort();//關閉時切斷進程 ? ? ? ? ? ? } ? ? ? ? ? ? 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(); ? ? ? ? } ? ? } }
可以正常對話,測試一下。假裝和自己對話
目前還沒有解決沾包問題
原文鏈接:https://blog.csdn.net/qq_38061677/article/details/81226818
相關推薦
- 2023-01-19 使用python檢查值是否已經存在于字典列表中_python
- 2022-11-30 簡易的redux?createStore手寫實現示例_React
- 2022-04-12 安裝zsh&oh-my-zsh(沒有root權限)
- 2023-11-14 MathType 運行時錯誤‘53’:文件未找到:MathPage.WLL
- 2022-08-06 SQL?Server備份數據庫的完整步驟_MsSql
- 2022-12-04 Python中的配對函數zip()解讀_python
- 2022-06-18 Android?Recyclerview實現左滑刪除功能_Android
- 2022-10-07 react性能優(yōu)化useMemo與useCallback使用對比詳解_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支