protected TcpChannel(int channelId) : base(channelId) { _receivingBufferSize = 32 * 1024; _sendingBlocking = new ManualResetEventSlim(true); _sendingCounter = new ConcurrentDictionary<long, PackingState>(); _sendingAsyncArgsPool = new SocketAsyncEventArgsPool(SocketAsyncEventArgs_Completed); }
public FtpPasvDataChannel(int bufferSize) { var buffer = new byte[bufferSize]; _receiveArgs = new SocketAsyncEventArgs(); _receiveArgs.SetBuffer(buffer, 0, buffer.Length); _receiveArgs.Completed += OnReceiveCompleted; _acceptArgs = new SocketAsyncEventArgs(); _acceptArgs.Completed += OnAcceptCompleted; _sendArgsPool = new SocketAsyncEventArgsPool(OnSendCompleted); }
// Create an uninitialized server instance. // To start the server listening for connection requests // call the Init method followed by Start method // // <param name="numConnections">the maximum number of connections the sample is designed to handle simultaneously</param> // <param name="receiveBufferSize">buffer size to use for each socket I/O operation</param> public Server(int numConnections, int receiveBufferSize) { m_totalBytesRead = 0; m_numConnectedSockets = 0; m_numConnections = numConnections; m_receiveBufferSize = receiveBufferSize; // allocate buffers such that the maximum number of sockets can have one outstanding read and //write posted to the socket simultaneously m_bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToPreAlloc, receiveBufferSize); m_readWritePool = new SocketAsyncEventArgsPool(numConnections); m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections); }
public FtpPortDataChannel(IPEndPoint address, int bufferSize) { if (address == null) throw new ArgumentNullException("address"); _address = address; var buffer = new byte[bufferSize]; _receiveArgs = new SocketAsyncEventArgs(); _receiveArgs.SetBuffer(buffer, 0, buffer.Length); _receiveArgs.Completed += OnReceiveCompleted; _connectArgs = new SocketAsyncEventArgs(); _connectArgs.Completed += OnConnectCompleted; _sendArgsPool = new SocketAsyncEventArgsPool(OnSendCompleted); }
private TcpOpenServer.SendState send() { #if !DOTNET2 START: #endif if (IsSocket) { #if DOTNET2 SocketError socketError; if (onSendAsyncCallback == null) onSendAsyncCallback = onSend; Socket.BeginSend(sendData.Array, sendData.Start, sendData.Length, SocketFlags.None, out socketError, onSendAsyncCallback, Socket); if (socketError == SocketError.Success) return TcpOpenServer.SendState.Asynchronous; #else if (sendAsyncEventArgs == null) { sendAsyncEventArgs = SocketAsyncEventArgsPool.Get(); sendAsyncEventArgs.Completed += onSend; } #if !DotNetStandard while (Interlocked.CompareExchange(ref sendAsyncLock, 1, 0) != 0) Thread.Sleep(0); #endif sendAsyncEventArgs.SetBuffer(sendData.Array, sendData.Start, sendData.Length); if (Socket.SendAsync(sendAsyncEventArgs)) { #if !DotNetStandard Interlocked.Exchange(ref sendAsyncLock, 0); #endif return TcpOpenServer.SendState.Asynchronous; } if (sendAsyncEventArgs.SocketError == SocketError.Success) { sendData.MoveStart(sendAsyncEventArgs.BytesTransferred); #if !DotNetStandard Interlocked.Exchange(ref sendAsyncLock, 0); #endif if (sendData.Length == 0) { freeCopyBuffer(); return TcpOpenServer.SendState.Synchronize; } goto START; } #endif } return TcpOpenServer.SendState.Error; }
public TCPServer(string serverName, IPEndPoint bindTo, int MaxConnections) { ServerName = "[" + serverName + "]"; // Create our Socket Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Set Socket options Listener.LingerState = new LingerOption(enable: false, seconds: 0); Listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); // Bind to our port Listener.Bind(bindTo); Listener.Listen(25); // Set the rest of our internals MaxNumConnections = MaxConnections; MaxConnectionsEnforcer = new SemaphoreSlim(MaxNumConnections, MaxNumConnections); SocketAcceptPool = new SocketAsyncEventArgsPool(ConcurrentAcceptPoolSize); SocketReadWritePool = new SocketAsyncEventArgsPool(MaxNumConnections * 2); // Create our Buffer Manager for IO operations. // Always allocate double space, one for recieving, and another for sending BufferManager = new BufferManager(MaxNumConnections * 2, BufferSizePerOperation); // Assign our Connection Accept SocketAsyncEventArgs object instances for (int i = 0; i < ConcurrentAcceptPoolSize; i++) { SocketAsyncEventArgs SockArg = new SocketAsyncEventArgs(); SockArg.Completed += (s, e) => PrepareAccept(e); // Do NOT assign buffer space for Accept operations! SocketAcceptPool.Push(SockArg); } // Assign our Connection IO SocketAsyncEventArgs object instances for (int i = 0; i < MaxNumConnections * 2; i++) { SocketAsyncEventArgs SockArg = new SocketAsyncEventArgs(); BufferManager.AssignBuffer(SockArg); SocketReadWritePool.Push(SockArg); } // set public internals IsListening = true; }
public CoCServer() { _settings = new NetworkManagerAsyncSettings(50, 50); _listener = new Socket(SocketType.Stream, ProtocolType.Tcp); _acceptPool = new SocketAsyncEventArgsPool(100); AvatarManager = new AvatarManager(); DataManager = new DataManager(); Clients = new List<CoCRemoteClient>(); MessageHandlers = new Dictionary<ushort, MessageHandler>(); CommandHandlers = new Dictionary<int, CommandHandler>(); LoginMessageHandlers.RegisterLoginMessageHandlers(this); InGameMessageHandlers.RegisterInGameMessageHandlers(this); BuildingCommandHandlers.RegisterBuildingCommandHandlers(this); AvatarManager.LoadAllAvatars(); }
// Create an uninitialized server instance. // To start the server listening for connection requests // call the Init method followed by Start method // // <param name="numConnections">the maximum number of connections the sample is designed to handle simultaneously</param> // <param name="receiveBufferSize">buffer size to use for each socket I/O operation</param> // <param name="ReceiveCallBack">接收到消息的回调函数</param> public MicrosoftServer(int numConnections, int receiveBufferSize, ReceiveCallBack rcb) { m_totalBytesRead = 0; m_numConnectedSockets = 0; m_numConnections = numConnections; m_receiveBufferSize = receiveBufferSize; receiveCallBack = rcb; // allocate buffers such that the maximum number of sockets can have one outstanding read and //write posted to the socket simultaneously m_bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToPreAlloc, receiveBufferSize); m_readPool = new SocketAsyncEventArgsPool(numConnections); m_writePool = new SocketAsyncEventArgsPool(numConnections); m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections); m_buffer = new List <Byte>(); }
// Create an uninitialized server instance. // To start the server listening for connection requests // call the Init method followed by Start method // // <param name="numConnections">the maximum number of connections the sample is designed to handle simultaneously</param> // <param name="receiveBufferSize">buffer size to use for each socket I/O operation</param> public void Construct(int numConnections, int receiveBufferSize) { m_commandParser = GetComponent <CommandParser>(); m_totalBytesRead = 0; m_numConnectedSockets = 0; m_numConnections = numConnections; // allocate buffers such that the maximum number of sockets can have one outstanding read and //write posted to the socket simultaneously m_bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToPreAlloc, receiveBufferSize); m_readWritePool = new SocketAsyncEventArgsPool(numConnections); m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections); m_receiveBufferSize = receiveBufferSize; m_bufferHelper = new BufferHelper(); }
public UdpSession(uint sid, SocketAsyncEventArgsPool pool, ISessionListener listener) { LOG_TAG = "UdpSession[" + sid + "]"; this.Log(); onSendError = new Signal <ISession, int>(); onReceiveError = new Signal <ISession, int>(); m_pool = pool; m_queueSend = new Queue <NetPacket>(); m_bufferSend = new NetBufferWriter(new byte[0]); m_queueReceive = new Queue <NetMessage>(); this.Id = sid; m_listener = listener; }
/// <summary> /// 异步Socket TCP服务器 /// </summary> /// <param name="localIPAddress">监听的IP地址</param> /// <param name="portNo">监听的端口</param> /// <param name="maxClient">最大客户端数量</param> public IOCPServer(string IP, int portNo, int maxClient) { //this.Address = localIPAddress; //this.Port = listenPort; //this.Encoding = Encoding.Default; //_serverSock = new Socket(localIPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); //_bufferManager = new BufferManager(_bufferSize * maxClient * opsToPreAlloc, _bufferSize); //_objectPool = new SocketAsyncEventArgsPool(maxClient); //_maxAcceptedClients = new Semaphore(maxClient, maxClient); Console.WriteLine("初始化服务器。"); try { IPAddress ipAddress = IPAddress.Parse(IP); _serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _serverSock.Bind(new IPEndPoint(ipAddress, portNo)); _serverSock.Listen(maxClient); _objectPool = new SocketAsyncEventArgsPool(maxClient); for (int i = 0; i < maxClient; i++) //填充SocketAsyncEventArgs池 { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += new EventHandler <SocketAsyncEventArgs>(OnIOCompleted); _objectPool.Add(args); } Thread tCheckClientHeartbeat = new Thread(CheckClientHeartbeat); tCheckClientHeartbeat.IsBackground = true; tCheckClientHeartbeat.Start(); StartAccept(null); } catch (Exception error) { Console.WriteLine(error.Message); } }
private void InitStart() { if (Interlocked.CompareExchange(ref _isListened, 1, 0) != 0) { return; } listen?.Close(); listen = GetNewSocketInfo(); listen.Bind(new IPEndPoint(IPAddress.Parse(this.listen_ip), this.listen_port)); listen.Listen(100); var e = SocketAsyncEventArgsPool.GetNewAsyncEventArgs(); accept_listen_async_arg = e; e.Completed += (S, EE) => { AcceptAsyncCallback(listen, EE); }; ProessAccept(listen, e); }
public MultiplayerClient(TrueCraftUser user) { User = user; Client = new TcpClient(); PacketReader = new PacketReader(); PacketReader.RegisterCorePackets(); PacketHandlers = new PacketHandler[0x100]; Handlers.PacketHandlers.RegisterHandlers(this); World = new ReadOnlyWorld(); var repo = new BlockRepository(); repo.DiscoverBlockProviders(); World.World.BlockRepository = repo; World.World.ChunkProvider = new EmptyGenerator(); Physics = new PhysicsEngine(World, repo); SocketPool = new SocketAsyncEventArgsPool(100, 200, 65536); connected = 0; cancel = new CancellationTokenSource(); }
//========================================================== //构造函数 //========================================================== public TcpConnection(int localPort, SocketAsyncEventArgsPool pool, int maxReconnCnt = 0) : base(pool) { LOG_TAG = "TcpConnection[" + 0 + "," + localPort + "]"; this.Log("connId:{0}, localPort:{1}, maxReconnCnt", 0, localPort, maxReconnCnt); m_maxReconnCnt = maxReconnCnt; onReceive = new Signal <NetMessage>(); onConnectSuccess = new Signal <IConnection>(); onConnectError = new Signal <IConnection, int>(); onDisconnected = new Signal <IConnection>(); onSendSuccess = new Signal <IConnection>(); onSendError = new Signal <IConnection, int, string>(); onConnecting = new Signal <IConnection>(); onReceiveError = new Signal <IConnection, int, string>(); onServerError = new Signal <IConnection, int, string>(); m_listRemoteEndPoint = new List <IPEndPoint>(); m_currRemoteEndPointIndex = -1; m_localPort = localPort; }
private void InitStartIpv6() { if (Interlocked.CompareExchange(ref _isListened, 1, 0) != 0) { return; } listen?.Close(); listen = GetNewSocketInfo(); if (Net.SocketHelper.PortInUse(this.listen_port)) { var pro = Net.SocketHelper.PortInUseProcess(this.listen_port); if (pro != null) { throw new System.Exception($@"服务端口【{ this.listen_port}】已经被其他进程占用。占用进程信息: PID:{pro.Id} ProcessName:{pro.ProcessName}"); } } listen.Bind(new IPEndPoint(IPAddress.Any, this.listen_port)); listen.Listen(100); var e = SocketAsyncEventArgsPool.GetNewAsyncEventArgs(); accept_listen_async_arg = e; e.Completed += (S, EE) => { AcceptAsyncCallback(listen, EE); }; ProessAccept(listen, e); listenIPv6?.Close(); listenIPv6 = GetNewSocketIPv6Info(); listenIPv6.Bind(new IPEndPoint(IPAddress.IPv6Any, this.listen_port)); listenIPv6.Listen(100); var e_ipv6 = SocketAsyncEventArgsPool.GetNewAsyncEventArgs(); accept_listen_IPv6_async_arg = e_ipv6; e_ipv6.Completed += (S, EE) => { AcceptAsyncCallback(listenIPv6, EE); }; ProessAccept(listenIPv6, e_ipv6); }
public FtpPortDataChannel(IPEndPoint address, int bufferSize) { if (address == null) { throw new ArgumentNullException("address"); } _address = address; var buffer = new byte[bufferSize]; _receiveArgs = new SocketAsyncEventArgs(); _receiveArgs.SetBuffer(buffer, 0, buffer.Length); _receiveArgs.Completed += OnReceiveCompleted; _connectArgs = new SocketAsyncEventArgs(); _connectArgs.Completed += OnConnectCompleted; _sendArgsPool = new SocketAsyncEventArgsPool(OnSendCompleted); }
public void Init() { m_maxConnection = 10000; m_bufferSize = 1024; // 동시커넥션 할 클라이언트 갯수 * 클라이언트별 패킷 버퍼의 사이즈 * 미리 잡아놓을 풀 사이즈 // 풀 사이즈는 read, write 총 2개 m_bufferManager = new BufferManager(m_maxConnection * m_bufferSize * m_preAllocCount, m_bufferSize); m_receiveEventArgsPool = new SocketAsyncEventArgsPool(m_maxConnection); m_sendEventArgsPool = new SocketAsyncEventArgsPool(m_maxConnection); m_bufferManager.InitBuffer(); SocketAsyncEventArgs args; for (int i = 0; i < m_maxConnection; i++) { // 동일한 소켓에 send 및 receive // 유저 토큰은 클라이언트 세션 당 한개 생성 후 // 각 eventArgs에서 동일한 토큰을 가지게 한 후 참조하도록 함 CustomUserToken token = new CustomUserToken(); { // receive pool args = new SocketAsyncEventArgs(); args.Completed += new EventHandler <SocketAsyncEventArgs>(OnReceiveCompleted); args.UserToken = token; m_bufferManager.SetBuffer(args); m_receiveEventArgsPool.Push(args); } { // send pool args = new SocketAsyncEventArgs(); args.Completed += new EventHandler <SocketAsyncEventArgs>(OnSendCompleted); args.UserToken = token; m_bufferManager.SetBuffer(args); m_sendEventArgsPool.Push(args); } } }
public void PopPush_Disposed_Exception() { var pool = new SocketAsyncEventArgsPool(64); // Populate the pool. for (int i = 0; i < 64; i++) { pool.Push(new SocketAsyncEventArgs()); } // Remove a couple of the args. for (int i = 0; i < 32; i++) { pool.Pop(); } pool.Dispose(); Assert.Throws <ObjectDisposedException>(() => pool.Push(new SocketAsyncEventArgs())); Assert.Throws <ObjectDisposedException>(() => pool.Pop()); }
public SocketServer(int numConnections, int receiveBufferSize) { myMessageHandler = new MessageHandler(connectionString); m_numConnections = numConnections; m_receiveBufferSize = receiveBufferSize; // allocate buffers such that the maximum number of sockets can have one outstanding read and //write posted to the socket simultaneously // m_bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToPreAlloc, // receiveBufferSize); m_readWritePool = new SocketAsyncEventArgsPool(numConnections); // m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections); SqlDataReader dr = null; try { SQLManager.SQLManager mySql = new SQLManager.SQLManager(connectionString); dr = mySql.getDataReader("EXEC getGroups"); while (dr.Read()) { System.Collections.ArrayList userList = new System.Collections.ArrayList(); string users = (string)dr["Users"]; string[] userArr = users.Split((",".ToCharArray())); for (int i = 0; i<userArr.Length-1; i++) { userList.Add(long.Parse(userArr[i])); } groupLookup.Add((long)dr["GPID"], userList); } } catch { } finally { if (dr != null) dr.Close(); } }
/// <summary> /// Initialize and start the server. /// </summary> public void Start() { if (this._isRunning) { throw new InvalidOperationException("Server is already running."); } if (this.Configuration.Port <= 0) { throw new EtherConfigurationException($"{this.Configuration.Port} is not a valid port."); } var address = this.Configuration.Address; if (address == null) { throw new EtherConfigurationException($"Invalid host : {this.Configuration.Host}"); } this._bufferManager = new BufferManager(this.Configuration.MaximumNumberOfConnections, this.Configuration.BufferSize); if (this._readPool == null) { this._readPool = new SocketAsyncEventArgsPool(this.Configuration.MaximumNumberOfConnections); } if (this._writePool == null) { this._writePool = new SocketAsyncEventArgsPool(this.Configuration.MaximumNumberOfConnections); } this.Initialize(); this.Socket.Bind(new IPEndPoint(address, this.Configuration.Port)); this.Socket.Listen(this.Configuration.Backlog); this.StartAccept(); this._isRunning = true; this._resetEvent.WaitOne(); }
public UDPServer(string serverName, IPEndPoint bindTo, int MaxConnections) { ServerName = "[" + serverName + "]"; // Create our Socket this.Port = Port; Listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { SendTimeout = 5000, // We have a limited pool, so we dont want to be locked often SendBufferSize = BufferSizePerEvent, ReceiveBufferSize = BufferSizePerEvent }; // Bind to our port Listener.Bind(bindTo); // Set the rest of our internals MaxNumConnections = MaxConnections; MaxConnectionsEnforcer = new SemaphoreSlim(MaxNumConnections, MaxNumConnections); SocketReadWritePool = new SocketAsyncEventArgsPool(MaxNumConnections); // Create our Buffer Manager for IO operations. BufferManager = new BufferManager( MaxNumConnections, BufferSizePerEvent ); // Assign our Connection IO SocketAsyncEventArgs object instances for (int i = 0; i < MaxNumConnections; i++) { SocketAsyncEventArgs SockArg = new SocketAsyncEventArgs(); SockArg.Completed += IOComplete; BufferManager.AssignBuffer(SockArg); SocketReadWritePool.Push(SockArg); } // set public internals IsRunning = true; Disposed = false; }
public RemoteClient(IMultiplayerServer server, IPacketReader packetReader, PacketHandler[] packetHandlers, Socket connection) { LoadedChunks = new HashSet <Coordinates2D>(); Server = server; Inventory = new InventoryWindow(server.CraftingRepository); InventoryWindow.WindowChange += HandleWindowChange; SelectedSlot = InventoryWindow.HotbarIndex; CurrentWindow = InventoryWindow; ItemStaging = ItemStack.EmptyStack; KnownEntities = new List <IEntity>(); Disconnected = false; EnableLogging = server.EnableClientLogging; NextWindowID = 1; Connection = connection; SocketPool = new SocketAsyncEventArgsPool(100, 200, 65536); PacketReader = packetReader; PacketHandlers = packetHandlers; cancel = new CancellationTokenSource(); StartReceive(); }
//========================================================== //构造函数 //========================================================== public UdpConnection(int localPort, SocketAsyncEventArgsPool pool) { LOG_TAG = "UdpConnection[" + 0 + "," + localPort + "]"; this.Log("connId:{0}, localPort:{1}", 0, localPort); onReceive = new Signal <NetMessage>(); onSendError = new Signal <IConnection, int, string>(); onReceiveError = new Signal <IConnection, int, string>(); onServerError = new Signal <IConnection, int, string>(); m_listRemoteEndPoint = new List <IPEndPoint>(); m_currRemoteEndPointIndex = -1; m_pool = new SocketAsyncEventArgsPool(NetDefine.PacketBufferSize, 0); m_queueSend = new Queue <NetPacket>(); m_bufferSend = new NetBufferWriter(new byte[0]); m_queueReceive = new Queue <NetMessage>(); m_bufferReceive = new NetBufferWriter(new byte[NetDefine.ReceiveBufferMinSize]); m_localPort = localPort; }
/// <summary> /// 释放接收数据缓冲区与异步事件对象 /// </summary> private void close() { isClose = true; try { #if DOTNET2 DisposeSocket(); #else if (receiveAsyncEventArgs == null) DisposeSocket(); else { receiveAsyncEventArgs.Completed -= onReceive; DisposeSocket(); SocketAsyncEventArgsPool.PushNotNull(ref receiveAsyncEventArgs); } #endif } catch (Exception error) { ClientCreator.CommandClient.AddLog(error); } CloseFree(); }
/// <summary> /// 释放接收数据缓冲区与异步事件对象 /// </summary> private void close() { try { #if DOTNET2 DisposeSocket(); #else if (receiveAsyncEventArgs == null) DisposeSocket(); else { receiveAsyncEventArgs.Completed -= onReceive; DisposeSocket(); SocketAsyncEventArgsPool.PushNotNull(ref receiveAsyncEventArgs); } #endif } catch (Exception error) { Server.AddLog(error); } CloseFree(); if (Sender != null) Sender.Close(); }
/// <summary> /// 释放资源 /// </summary> public override void Dispose() { #if DOTNET2 if (onReceiveAsyncCallback != null) #else if (receiveAsyncEventArgs != null) #endif { #if DOTNET2 onReceiveAsyncCallback = onSendAsyncCallback = null; #else receiveAsyncEventArgs.Completed -= onReceiveAsyncCallback; sendAsyncEventArgs.Completed -= onSendAsyncCallback; SocketAsyncEventArgsPool.PushNotNull(ref receiveAsyncEventArgs); SocketAsyncEventArgsPool.PushNotNull(ref sendAsyncEventArgs); #endif Buffer.Free(); Header.Free(); #if !DOTNET2 if (boundaryReceiver == null) boundaryReceiver.Free(); #endif } }
public static SerializeResult Serialize() { try { var MaxConnections = int.Parse(Settings.GetValue("TCP.Listener.Max")); Counter = 0; Sessions = new Dictionary <int, Session>(); SocketPool = new SocketAsyncEventArgsPool(MaxConnections); ConnectedAmount = new int(); SocketSemaphore = new Semaphore(MaxConnections, MaxConnections); BufferManager = new BufferManager(RECV_BUFFER_SIZE * MaxConnections * OPS_TO_PRE_ALLOC, RECV_BUFFER_SIZE); Solution.AppendLine("SessionHandler: Pushing SocketAsync({0}), big-buffer({1})", MaxConnections, BufferManager.Buffer.Length); for (int i = 0; i < MaxConnections; i++) { var Async = new SocketAsyncEventArgs(); Async.Completed += new EventHandler <SocketAsyncEventArgs>(Async_Completed); Async.UserToken = new AsyncUserToken(); BufferManager.SetBuffer(Async); SocketPool.Push(Async); } var IPEndPoint = new IPEndPoint(IPAddress.Parse(Settings.GetValue("TCP.Listener.IP")), int.Parse(Settings.GetValue("TCP.Listener.Port"))); BaseSocket = new Socket(IPEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); BaseSocket.Bind(IPEndPoint); BaseSocket.Listen(int.Parse(Settings.GetValue("TCP.Listener.Backlog"))); WaitForAsync(null); } catch { return(SerializeResult.Broken); } return(SerializeResult.Finished); }
public void Init(int maxClient) { connTimeOut = new UpdClientTimeOut(); connTimeOut.TimeOut = 1800; connTimeOut.Start(); dataPacketManager = new YDataPacketManager(); YDataPacketManager.RegisterDataPacket(typeof(SocketRegisterPacket)); dataPacketManager.DataPacketReceived += dataPacketManager_DataPacketReceived; this.maxClient = maxClient + 1; socketPool = new SocketAsyncEventArgsPool(maxClient); SocketAsyncEventArgs readWriteEventArg; bufferManager = new BufferManager(maxClient * bufferLenthg, bufferLenthg); bufferManager.InitBuffer(); for (int i = 0; i < maxClient; i++) { readWriteEventArg = new SocketAsyncEventArgs(); readWriteEventArg.Completed += readWriteEventArg_Completed; bufferManager.SetBuffer(readWriteEventArg); socketPool.Push(readWriteEventArg); } AbsInit(); isInit = true; }
public void ShutdownServer() { KSPMGlobals.Globals.Log.WriteTo("Shuttingdown the KSPM server ."); ///*************************Killing threads code this.alive = false; this.commandsThread.Abort(); this.outgoingMessagesThread.Abort(); this.localCommandsThread.Abort(); this.priorityOutgoingMessagesThread.Abort(); this.commandsThread.Join(); KSPMGlobals.Globals.Log.WriteTo("Killed commandsTread ."); this.localCommandsThread.Join(); KSPMGlobals.Globals.Log.WriteTo("Killed localCommandsTread ."); this.outgoingMessagesThread.Join(); KSPMGlobals.Globals.Log.WriteTo("Killed outgoingMessagesTread ."); this.priorityOutgoingMessagesThread.Join(); KSPMGlobals.Globals.Log.WriteTo("Killed priorityOutgoingMessagesTread ."); ///*************************Killing TCP socket code if (this.tcpSocket.Connected) { this.tcpSocket.Shutdown(SocketShutdown.Both); this.tcpSocket.Close(); } this.tcpBuffer = null; this.tcpIpEndPoint = null; KSPMGlobals.Globals.Log.WriteTo("Killing chat system!!!"); this.chatManager.Release(); this.chatManager = null; KSPMGlobals.Globals.Log.WriteTo("Killing conected clients!!!"); this.clientsHandler.Release(); this.clientsHandler = null; ///*********************Killing server itself this.ableToRun = false; ///Releasing command queues. this.commandsQueue.Purge(false); this.outgoingMessagesQueue.Purge(false); this.localCommandsQueue.Purge(false); this.priorityOutgoingMessagesQueue.Purge(false); this.commandsQueue = null; this.localCommandsQueue = null; this.outgoingMessagesQueue = null; this.priorityOutgoingMessagesQueue = null; ///Releasing messages pools. this.priorityMessagesPool.Release(); this.incomingMessagesPool.Release(); this.priorityMessagesPool = null; this.incomingMessagesPool = null; ///Releasing SAEA pool. this.incomingConnectionsPool.Release(false); this.incomingConnectionsPool = null; this.usersAccountManager = null; this.lowLevelOperationSettings = null; ///Releasing the TCP purge timer. this.tcpPurgeTimer.Dispose(); this.tcpPurgeTimer = null; KSPMGlobals.Globals.Log.WriteTo(string.Format("Server KSPM killed after {0} miliseconds alive!!!", RealTimer.Timer.ElapsedMilliseconds)); #if PROFILING this.profilerOutgoingMessages.Dispose(); #endif }
public void Listen() { // If you call listen() on a port, then kill the process, then immediately start a new process and // try to listen() on the same port, you sometimes get WSAEADDRINUSE. Even if nothing was accepted. // Ports don't immediately free themselves on process shutdown. We call listen() in a loop on a delay // for a few iterations for this reason. // TimeSpan listenTimeout = TimeSpan.FromSeconds(1); BackoffTimeoutHelper backoffHelper = new BackoffTimeoutHelper(listenTimeout); lock (ThisLock) { if (this.listenSocket != null) { this.listenSocket.Listen(settings.ListenBacklog); isListening = true; } while (!isListening) { try { this.listenSocket = new Socket(localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (localEndpoint.AddressFamily == AddressFamily.InterNetworkV6 && settings.TeredoEnabled) { this.listenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)23, 10); } this.listenSocket.Bind(localEndpoint); this.listenSocket.Listen(settings.ListenBacklog); isListening = true; } catch (SocketException socketException) { bool retry = false; if (socketException.ErrorCode == UnsafeNativeMethods.WSAEADDRINUSE) { if (!backoffHelper.IsExpired()) { backoffHelper.WaitAndBackoff(); retry = true; } } if (!retry) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( SocketConnectionListener.ConvertListenException(socketException, this.localEndpoint)); } } } this.socketAsyncEventArgsPool = new SocketAsyncEventArgsPool(GetAcceptBufferSize(this.listenSocket)); } }
/// <summary> /// 设置基本配置 /// </summary> /// <param name="receiveBufferSize">用于每个套接字I/O操作的缓冲区大小(接收端)</param> internal TcpClients(int receiveBufferSize) { m_receiveBufferSize = receiveBufferSize; m_sendPool = new SocketAsyncEventArgsPool(m_minSendSocketAsyncEventArgs); Init(); }
public HttpSocketServer(RemoteCommands remoteCommands) { logger = new Logger("HttpServer", false); InitSettings(); m_remoteCommands = remoteCommands; numConnectedSockets = 0; bufferManager = new BufferManager((receiveBufferSize + sendBufferSize) * numberOfEventArgsForRecSend, receiveBufferSize + sendBufferSize); poolOfAcceptEventArgs = new SocketAsyncEventArgsPool(maxSimultaneousAcceptOps); poolOfRecSendEventArgs = new SocketAsyncEventArgsPool(numberOfEventArgsForRecSend); maxNumberAcceptedClients = new Semaphore(maxConnections, maxConnections); }
/// <summary> /// 创建 TCP 服务客户端套接字 /// </summary> internal override void Create() { bool isErrorLog = false, isReceiveAsync = false; socketError = SocketError.Success; do { if (checkCreate() == 0) return; if (isSleep) { isSleep = false; Thread.Sleep(ClientCreator.CommandClient.TryCreateSleep); if (checkCreate() == 0) return; } try { Socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); #if !MONO Socket.ReceiveBufferSize = ClientCreator.CommandClient.ReceiveBufferPool.Size; Socket.SendBufferSize = ClientCreator.CommandClient.SendBufferPool.Size; #endif Socket.Connect(ipAddress, port); if (checkCreate() == 0) return; #if DOTNET2 if (onReceiveAsyncCallback == null) onReceiveAsyncCallback = onReceive; #else if (receiveAsyncEventArgs == null) { receiveAsyncEventArgs = SocketAsyncEventArgsPool.Get(); receiveAsyncEventArgs.Completed += onReceive; } #endif if (ReceiveBuffer.Buffer == null) ClientCreator.CommandClient.ReceiveBufferPool.Get(ref ReceiveBuffer); if (Sender == null) SetSender(new ClientSocketSender(this)); receiveBufferSize = ReceiveBuffer.PoolBuffer.Pool.Size; receiveCount = receiveIndex = 0; ReceiveType = TcpServer.ClientSocketReceiveType.CommandIdentity; #if DOTNET2 Socket.BeginReceive(ReceiveBuffer.Buffer, ReceiveBuffer.StartIndex, receiveBufferSize, SocketFlags.None, out socketError, onReceiveAsyncCallback, Socket); if (socketError == SocketError.Success) #else #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 1); #endif receiveAsyncEventArgs.SetBuffer(ReceiveBuffer.Buffer, ReceiveBuffer.StartIndex, receiveBufferSize); if (Socket.ReceiveAsync(receiveAsyncEventArgs)) #endif { #if !DOTNET2 && !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock, 0); #endif isReceiveAsync = true; if (verifyMethod(ClientCreator.CommandClient)) { if (ClientCreator.OnSocketVerifyMethod(this)) { if (isErrorLog) { ClientCreator.CommandClient.Log.Add(AutoCSer.Log.LogType.Debug, ClientCreator.Attribute.ServerName + " 客户端 TCP 连接成功 " + ipAddress.ToString() + ":" + port.toString()); } return; } } if (Socket != null) { #if DotNetStandard AutoCSer.Net.TcpServer.CommandBase.CloseClientNotNull(Socket); #else Socket.Dispose(); #endif Socket = null; } return; } } catch (Exception error) { if (!isErrorLog) { isErrorLog = true; ClientCreator.CommandClient.Log.Add(AutoCSer.Log.LogType.Debug, error, ClientCreator.Attribute.ServerName + " 客户端 TCP 连接失败 " + ipAddress.ToString() + ":" + port.toString()); } } if (isReceiveAsync) return; CreateSleep(); } while (true); }
/// <summary> /// Initializes a new instance of the <see cref="UdpServerEapBase{TServerClient}" /> class. /// </summary> /// <param name="expectedMaxPayloadSize"> (Optional) Size of the expected maximum payload. </param> protected UdpServerEapBase(ushort expectedMaxPayloadSize = Constants.UDP_PAYLOAD_SIZE_MAX) : base(expectedMaxPayloadSize) { _receiveEventArgsPool = new SocketAsyncEventArgsPool(0xFF); _sendEventArgsPool = new SocketAsyncEventArgsPool(0xFF); }
/// <summary> /// Initializes a new instance of the <see cref="UdpClientEap" /> class. /// </summary> /// <param name="expectedMaxPayloadSize"> (Optional) Size of the expected maximum payload. </param> public UdpClientEap(ushort expectedMaxPayloadSize = Constants.UDP_PAYLOAD_SIZE_MAX) : base(expectedMaxPayloadSize) { _receiveEventArgsPool = new SocketAsyncEventArgsPool(); _sendEventArgsPool = new SocketAsyncEventArgsPool(); }
private void Initialize() { this.totalBytesRead = 0; this.connectSocketNumber = 0; this.bufferManager = new BufferManager(bufferSize * connectNumber * 2, bufferSize); this.readWritePool = new SocketAsyncEventArgsPool(connectNumber); this.acceptClientMaxNumber = new Semaphore(connectNumber, connectNumber); bufferManager.InitBuffer(); SocketAsyncEventArgs readWriteEventArgs; for (int index = 0; index < connectNumber; index++) { readWriteEventArgs = new SocketAsyncEventArgs(); readWriteEventArgs.UserToken = new AsyncUserToken(); readWriteEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed); bufferManager.SetBuffer(readWriteEventArgs); readWritePool.Push(readWriteEventArgs); } }
/// <summary> /// 构造函数。 /// 初始化连接最大数量,内存池等结构。 /// </summary> public IocpServer(int numConnections) { this.numConnectedSockets = 0; this.numConnections = numConnections; this.readWritePool = new SocketAsyncEventArgsPool(3000); this.tokenMap = new Dictionary<long, IocpUserToken>(); for (Int32 i = 0; i < (this.numConnections * 2); i++) { // 申请一个SocketAsyncEventArgs结构,并添加到内存池。 this.readWritePool.Push(this.AllocSocketAsyncEventArgs()); } }
/// <summary> /// 构造方法 /// </summary> /// <param name="receiveBufferSize">接收缓存大小</param> public UdpServer(int receiveBufferSize) { m_receiveBufferSize = receiveBufferSize; m_sendPool = new SocketAsyncEventArgsPool(10); Init(); }
public void Listen() { BackoffTimeoutHelper helper = new BackoffTimeoutHelper(TimeSpan.FromSeconds(1.0)); lock (this.ThisLock) { if (this.listenSocket != null) { this.listenSocket.Listen(this.settings.ListenBacklog); this.isListening = true; } while (!this.isListening) { try { this.listenSocket = new Socket(this.localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if ((this.localEndpoint.AddressFamily == AddressFamily.InterNetworkV6) && this.settings.TeredoEnabled) { this.listenSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPProtectionLevel, 10); } this.listenSocket.Bind(this.localEndpoint); this.listenSocket.Listen(this.settings.ListenBacklog); this.isListening = true; continue; } catch (SocketException exception) { bool flag = false; if ((exception.ErrorCode == 0x2740) && !helper.IsExpired()) { helper.WaitAndBackoff(); flag = true; } if (!flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertListenException(exception, this.localEndpoint)); } continue; } } this.socketAsyncEventArgsPool = new SocketAsyncEventArgsPool(GetAcceptBufferSize(this.listenSocket)); } }
internal void Free() { socketAsyncEventArgs.Completed -= onReceiveAsyncCallback; SocketAsyncEventArgsPool.PushNotNull(ref socketAsyncEventArgs); }
/// <summary> /// 创建 TCP 服务客户端套接字 /// </summary> internal override void Create() { bool isErrorLog = false; socketError = SocketError.Success; do { if (checkCreate() == 0) return; if (isSleep) { isSleep = false; Thread.Sleep(ClientCreator.CommandClient.FristTryCreateSleep); } try { Socket = new Socket(IpAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); #if !MONO Socket.ReceiveBufferSize = ClientCreator.CommandClient.ReceiveBufferPool.Size; Socket.SendBufferSize = ClientCreator.CommandClient.SendBufferPool.Size; #endif Socket.Connect(IpAddress, Port); if (checkCreate() == 0) return; if (onReceiveAsyncCallback == null) onReceiveAsyncCallback = onReceive; #if !DOTNET2 if (receiveAsyncEventArgs == null) { receiveAsyncEventArgs = SocketAsyncEventArgsPool.Get(); receiveAsyncEventArgs.Completed += onReceiveAsyncCallback; } #endif if (ReceiveBuffer.Buffer == null) ClientCreator.CommandClient.ReceiveBufferPool.Get(ref ReceiveBuffer); if (Sender == null) SetSender(new ClientSocketSender(this)); receiveBufferSize = ReceiveBuffer.PoolBuffer.Pool.Size; receiveCount = receiveIndex = 0; ReceiveType = TcpServer.ClientSocketReceiveType.CommandIdentityAgain; #if DOTNET2 Socket.BeginReceive(ReceiveBuffer.Buffer, ReceiveBuffer.StartIndex, receiveBufferSize, SocketFlags.None, out socketError, onReceiveAsyncCallback, Socket); if (socketError == SocketError.Success) #else #if !DotNetStandard Interlocked.Exchange(ref receiveAsyncLock.Lock, 1); #endif receiveAsyncEventArgs.SetBuffer(ReceiveBuffer.Buffer, ReceiveBuffer.StartIndex, receiveBufferSize); if (Socket.ReceiveAsync(receiveAsyncEventArgs)) #endif { #if !DOTNET2 && !DotNetStandard receiveAsyncLock.Exit(); #endif if (verifyMethod() && ClientCreator.OnSocketVerifyMethod(this)) { if (isErrorLog) { ClientCreator.CommandClient.Log.Debug(ClientCreator.Attribute.ServerName + " 客户端 TCP 连接成功 " + IpAddress.ToString() + ":" + Port.toString(), LogLevel.Debug | LogLevel.AutoCSer); } ClientCreator.VerifyCount = 0; return; } } ++ClientCreator.VerifyCount; } catch (Exception error) { if (!isErrorLog) { isErrorLog = true; ClientCreator.CommandClient.Log.Exception(error, ClientCreator.Attribute.ServerName + " 客户端 TCP 连接失败 " + IpAddress.ToString() + ":" + Port.toString(), LogLevel.Exception | LogLevel.AutoCSer); } } if (Sender != null) { VerifyMethodSleep(); return; } ClientCreator.VerifyCount = 0; CreateSleep(); } while (true); }