您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要介绍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实现多人聊天功能”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。