using System.Collections.Concurrent; using System.Net; using System.Net.Sockets; using NetCore; using NetCore.ContentParse; using NetCore.NetServerCoreBasic; using NetCore.Protocol; namespace NetServer.NetLink.TCP; public class TCPServer : IServer where T : IContentParse where K : IProtocol { // private byte[] buffData = new byte[6553]; private Socket socket; public ILogicalParsing LogicalParsing { get { return _logicalParsing; } } private ILogicalParsing _logicalParsing; //记录半包数据 private bool isBufferData; private byte[] lastBuffData; private int lastCount; private short lastXueLieHao; //数据结束 //尾包 private byte[] weiBaoBuffData; private long index; private ConcurrentDictionary> allTcpServerConnections = new ConcurrentDictionary>(); private Thread _ConnectionUpdateThread; public TCPServer(int port, ILogicalParsing logicalParsing) { _logicalParsing = logicalParsing; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(IPAddress.Any, port)); socket.Listen(); AcceptAsync(); _ConnectionUpdateThread = new Thread(ConnectionUpdate); _ConnectionUpdateThread.Start(); } private void ConnectionUpdate() { while (socket != null) { long currTime = DateTime.Now.Ticks; foreach (var VARIABLE in allTcpServerConnections) { long lasetHearTime = VARIABLE.Value.HeartbeatLasetTime; if (currTime - lasetHearTime > 1200000000) //超时 { RemoveConnection(VARIABLE.Value); } } Thread.Sleep(1000); } } private async Task AcceptAsync() { try { if (socket == null) { return; } Socket newSocket = await socket.AcceptAsync(); AcceptAsync(); int code = newSocket.RemoteEndPoint.GetHashCode(); TCPServerConnection tcpServerConnection = new TCPServerConnection(this, newSocket); long currIndex = Interlocked.Add(ref index, 1); // long currIndex = index; tcpServerConnection.ConnectionId = currIndex; bool isAdd = allTcpServerConnections.TryAdd(currIndex, tcpServerConnection); if (!isAdd) { Console.Error.WriteLine("添加失败"); newSocket.Close(); newSocket.Dispose(); } else { _logicalParsing.AddConnection(tcpServerConnection); } } catch (Exception e) { Console.WriteLine(e); } } public void RemoveConnection(TCPServerConnection tcpServerConnection) { bool isOk = allTcpServerConnections.TryRemove(tcpServerConnection.ConnectionId, out TCPServerConnection value); if (!isOk) { Console.Error.WriteLine("移除失败"); } else { tcpServerConnection.Dispose(); _logicalParsing.RemoveConnection(tcpServerConnection); } } }