提高socket服务器响应速度,关于Socket服务器 谢谢大家 理解有限(大概200-500台设备作为客户端) 每台设备数据以每秒50MS的速度发送…

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Text.RegularExpressions;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Threading;namespaceConsoleApplication41

{classProgram

{

Socket serverSocket;string tempIP = "";

List ipaddrssList = new List();static void Main(string[] args)

{newProgram().ServerStar();

}///

///建立连接///

private voidServerStar()

{this.SocketServer("192.168.0.103", 4001);

}///

///服务端///

private void SocketServer(string host, intport)

{try{//服务器IP地址

IPAddress ip =IPAddress.Parse(host);

serverSocket= newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

serverSocket.Bind(newIPEndPoint(ip, port));

serverSocket.Listen(500);

Thread myThread= newThread(ListenClientConnect);

myThread.Start();

}catch(ArgumentNullException ex)

{

}catch(SocketException ex)

{

}

}///

///监听客户端连接///

private voidListenClientConnect()

{try{while (true)

{

Socket clientSocket=serverSocket.Accept();if (clientSocket.Connected == true)

{

Thread thread= new Thread(newParameterizedThreadStart(ReceiveMessage));

thread.Start(clientSocket);

}

}

}catch(Exception ex)

{

}

}///

///接收消息///

///

private void ReceiveMessage(objectclientSocket)

{

Socket myClientSocket=(Socket)clientSocket;

IPAddress clientIP=((IPEndPoint)myClientSocket.RemoteEndPoint).Address;

ByteQueue queue= newByteQueue();int temp = 0;while (true)

{try{byte[] recvBytes = new byte[1024];int bytes = myClientSocket.Receive(recvBytes, recvBytes.Length, 0);byte[] reallData = new byte[bytes];

Array.Copy(recvBytes, reallData, reallData.Length);

queue.Enqueue(reallData);while(queue.Find())

{byte[] readBuffer =queue.Dequeue();string data =BitConverter.ToString(readBuffer);if (data.StartsWith("FF-FF-FF-FF-CA-CB-CC-CD") && data.EndsWith("EA-EB-EC-ED"))

{string repStr = data.Replace("-", " ");

Regex regex= new Regex("07 81 08.{24}");

MatchCollection matches= regex.Matches(repStr, 0);if (matches.Count > 0)

{//显示消息

Console.WriteLine(repStr);

}

}

}

}catch(Exception ex)

{

}

}

}

}

}

THE END
< <上一篇
下一篇>>