protected virtual void onAccepted(System.IAsyncResult result) { TcpListener tcpListener = (TcpListener)result.AsyncState; Socket handler = null; try { if (!tcpListener.Server.IsBound) { return; } handler = tcpListener.EndAcceptSocket(result); ReactorHandler typeHandler = null; typeHandler = System.Activator.CreateInstance<TypeHandler>(); typeHandler.Handler = handler; lock (MainThreadLocker) { _handlers.Add(typeHandler); byte[] array = new byte[MaxReceiveSize]; var keyValuePair = new KeyValuePair<ReactorHandler, byte[]>(typeHandler, array); typeHandler.OnConnected(); typeHandler.BeginReceive(array, 0, MaxReceiveSize, this.onReceived, keyValuePair); } } catch (SocketException arg) { this.logger.Error("error in accepted\r\n" + arg); CloseSocket(handler); } tcpListener.BeginAcceptSocket(this.onAccepted, tcpListener); }
private void CloseHandler(ReactorHandler handler) { lock (MainThreadLocker) { _handlers.Remove(handler); handler.Close(); } }
protected virtual void onReceived(System.IAsyncResult result) { lock (MainThreadLocker) { var keyValuePair = (KeyValuePair<ReactorHandler, byte[]>)result.AsyncState; ReactorHandler reactorHandler = keyValuePair.Key; byte[] value = keyValuePair.Value; try { if (!_handlers.Contains(reactorHandler)) { return; } ReactorHandler key2 = keyValuePair.Key; int readCount = key2.EndReceive(result); if (readCount > 0) { byte[] array = new byte[readCount]; System.Buffer.BlockCopy(keyValuePair.Value, 0, array, 0, readCount); reactorHandler.OnReceived(array); reactorHandler.BeginReceive(value, 0, MaxReceiveSize, new System.AsyncCallback(this.onReceived), keyValuePair); } else { CloseHandler(reactorHandler); } } catch (System.Exception arg) { this.logger.Error("error in onReceived: \r\n" + arg); CloseHandler(reactorHandler); } } }