網站首頁 編程語言 正文
本文實例為大家分享了C#基于Socket實現多人聊天功能的具體代碼,供大家參考,具體內容如下
服務器
服務器負責接受所有客戶端發來的消息,和將接受到的問題群發到其他用戶。
代碼:
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);//接受用戶發送的內容 ? ? ? ? ? ? ? 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; //當前發送信息的客戶 ? ? ? ? ? ? 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(); ? ? ? ? } ? ? } }
客戶端
客戶端的功能開始十分簡單,可以發送信息給服務器。也可以接收服務器轉發過來其他客戶端的信息。
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
相關推薦
- 2022-01-30 h5 uniapp history模式下刷新頁面404
- 2022-06-01 Python正則表達式總結分享_python
- 2022-09-12 PyQt轉換路徑中的斜杠(斜杠(/)與反斜杠(\)轉換)_python
- 2021-12-28 vscode搭建go開發環境案例詳解_Golang
- 2022-07-28 Python知識點詳解之正則表達式語法_python
- 2022-10-03 Redis之SDS數據結構的使用_Redis
- 2022-11-27 C語言中花式退出程序的方式總結_C 語言
- 2023-02-12 Golang如何構造最佳隨機密碼詳解_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支