您的位置:首页 > 健康 > 美食 > 宣传推广费用预算_广州网页搜索排名提升_建网站免费_网络舆情监测

宣传推广费用预算_广州网页搜索排名提升_建网站免费_网络舆情监测

2024/12/26 19:27:35 来源:https://blog.csdn.net/XueZhiXia_/article/details/142566787  浏览:    关键词:宣传推广费用预算_广州网页搜索排名提升_建网站免费_网络舆情监测
宣传推广费用预算_广州网页搜索排名提升_建网站免费_网络舆情监测

 在主线程处理对所有客户端的连接以及消息处理,是非常消耗时间的,所以对于监听客户端的连接,以及信息的接收,都额外开线程去处理,减轻主线程的压力

using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;namespace TechTcpServerTest
{internal class Program{static Socket socket;static Socket socketClient;static List<Socket> socketClients = new List<Socket>();static void Main(string[] args){socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);try{IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);socket.Bind(ipPoint);}catch (Exception){return;                }socket.Listen(1024);Thread threadAccept = new Thread(AcceptClientConnect);threadAccept.Start();Thread threadResive = new Thread(ReceiveMsg);threadAccept.Start();while(true){if (Console.ReadLine() != "Quit"){return;}for(int i = 0; i < socketClients.Count; ++i){socketClients[i].Shutdown(SocketShutdown.Both);socketClients[i].Close();}socketClients.Clear();Console.WriteLine("所有连接已断开,socket套接字关闭");break;}Console.ReadLine();}static void AcceptClientConnect(){while (true){socketClient = socket.Accept();socketClients.Add(socketClient);if (socketClient.RemoteEndPoint != null){socketClient.Send(Encoding.UTF8.GetBytes($"{socketClient.RemoteEndPoint.ToString()}客户端已成功连接服务器"));}}}static void ReceiveMsg(){int i;int num;byte[] receiveBuffer = new byte[1024];while(true){for(i = 0; i < socketClients.Count; ++i){if (socketClients[i].Available > 0){num = socketClients[i].Receive(receiveBuffer);ThreadPool.QueueUserWorkItem(HandleMsg, (socketClients[i], Encoding.UTF8.GetString(receiveBuffer, 0, num)));}}}}static void HandleMsg(object obj){(Socket s, string str)info = ((Socket s, string str))obj;if (info.s.RemoteEndPoint != null){Console.WriteLine($"收到来次{info.s.RemoteEndPoint.ToString()}的消息:{info.str}");}}}
}

启动服务端,在unity中启动客户端,客户端最基本的代码在上一节,发现依旧可以正常连接,本节处理完毕

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com