好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#基于Socket实现多人聊天功能

本文实例为大家分享了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(); ? ? ? ? } ? ? } }

可以正常对话,测试一下。假装和自己对话

目前还没有解决沾包问题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于C#基于Socket实现多人聊天功能的详细内容...

  阅读:42次