在主线程处理对所有客户端的连接以及消息处理,是非常消耗时间的,所以对于监听客户端的连接,以及信息的接收,都额外开线程去处理,减轻主线程的压力
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中启动客户端,客户端最基本的代码在上一节,发现依旧可以正常连接,本节处理完毕
本文转载自: https://blog.csdn.net/XueZhiXia_/article/details/142566787
版权归原作者 yukino_NZB 所有, 如有侵权,请联系我们删除。
版权归原作者 yukino_NZB 所有, 如有侵权,请联系我们删除。