public void OnInitConnect(FTAPI_Conn client, long errCode, string desc) { if (client is FTAPI_Qot) { lock (qotLock) { if (errCode == 0) { qotConnStatus = ConnStatus.READY; Monitor.PulseAll(qotLock); } } } if (client is FTAPI_Trd) { lock (trdLock) { if (errCode == 0) { trdConnStatus = ConnStatus.READY; Monitor.PulseAll(trdLock); } } } }
public void Stop() { if (InPipe != null) { if (InPipe.IsConnected) { InPipe.Disconnect(); } InPipe.Close(); InPipe.Dispose(); InPipe = null; } if (OutPipe != null) { if (OutPipe.IsConnected) { OutPipe.Disconnect(); } OutPipe.Close(); OutPipe.Dispose(); OutPipe = null; } Status = ConnStatus.Disconnected; }
public SuperSpecialPictureBox() { InitializeComponent(); Status = ConnStatus.Default; pictureBox.Click += PictureBox_Click; }
private ArcUploadState taskUploadState; // the state of uploading archives according to the task /// <summary> /// Initializes a new instance of the class. /// </summary> public Exporter(ExportTargetConfig exporterConfig, EntityMap entityMap, IServerData serverData, AppDirs appDirs, string arcDir) { this.exporterConfig = exporterConfig ?? throw new ArgumentNullException(nameof(exporterConfig)); this.entityMap = entityMap ?? throw new ArgumentNullException(nameof(entityMap)); this.serverData = serverData ?? throw new ArgumentNullException(nameof(serverData)); this.arcDir = arcDir ?? throw new ArgumentNullException(nameof(arcDir)); GeneralOptions generalOptions = exporterConfig.GeneralOptions; dataLifetime = TimeSpan.FromSeconds(generalOptions.DataLifetime); string prefix = FilePrefix + "_" + generalOptions.ID.ToString("D3"); log = new Log(Log.Formats.Simple) { FileName = Path.Combine(appDirs.LogDir, prefix + ".log") }; infoFileName = Path.Combine(appDirs.LogDir, prefix + ".txt"); stateFileName = Path.Combine(appDirs.StorageDir, prefix + "_State.xml"); exporterTitle = string.Format("[{0}] {1}", generalOptions.ID, generalOptions.Name); dataSource = DataSourceFactory.GetDataSource(exporterConfig.ConnectionOptions); triggers = new ClassifiedTriggers(exporterConfig.Triggers, dataSource); thread = null; terminated = false; connStatus = ConnStatus.Undefined; CreateQueues(); InitArcUploading(); }
public void SendPacket(SendPacketBase packet) { if (!_socket.Connected) { _conStatus = ConnStatus.Closed; return; } MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); packet.Write(_sequence++, bw); byte[] data = ms.ToArray(); LogInterface.Log(string.Format("Sent Packet to client ({0}) {1}: {2}", AccountID, packet.ToString(), data.Length), LogInterface.LogMessageType.Debug); LogInterface.Log(Utils.PrintBinaryData(data), LogInterface.LogMessageType.Debug); _scSec.EncryptInPlace(data); ms = new MemoryStream(); bw = new BinaryWriter(ms); bw.Write((ushort)data.Length); bw.Write(data); _socket.Send(ms.ToArray()); bw.Close(); }
public void Disconnect() { if (_socket != null && _socket.Connected) { _socket.Close(); } _conStatus = ConnStatus.Closed; }
public virtual void Close() { if (_socket != null) { _socket.Close(); } _socket = null; _status = ConnStatus.Closed; }
//---------------------------------------------------------- // ConnectionStatusChanged handler //---------------------------------------------------------- public void OnConnStatus(ConnStatus connStatus) { //Show connect-status, and if connected show port we're using too AddResult(String.Format(" >Status: {0}{1}", connStatus.Status == eBTCONN_STATUS.BT_CONNECTION_COMPLETE ? "Connected" : connStatus.Status == eBTCONN_STATUS.BT_CONNECTION_LOST ? "Lost connection" : "Connection failed", connStatus.Status == eBTCONN_STATUS.BT_CONNECTION_COMPLETE ? "(" + connStatus.COMPort + ")" : "")); }
public Connection(Socket s) { _socket = s; _status = ConnStatus.New; _lastSeen = DateTime.Now; _lastSent = DateTime.Now; _packetHandlers = new Dictionary<UInt16, PacketHandler>(); RegisterPacketHandlers(); }
public Connection(Socket s) { _socket = s; _status = ConnStatus.New; _lastSeen = DateTime.Now; _lastSent = DateTime.Now; _packetHandlers = new Dictionary <UInt16, PacketHandler>(); RegisterPacketHandlers(); }
public void Update() { if (_socket != null) { if (!_socket.Connected && _status != ConnStatus.Disconnected) { _socket = null; _status = ConnStatus.Disconnected; } if (_socket.Connected) { // Read in packet data if (_socket.Available > 0) { _lastSeen = DateTime.Now; byte[] data = new byte[_socket.Available]; int bytesReceived = _socket.Receive(data); if (_pendingData != null) { _pendingData.AddRange(data); data = _pendingData.ToArray(); _pendingData = null; } ProcessPacketData(data); } // Are you still there? double timeSinceSeen = (DateTime.Now - _lastSeen).TotalSeconds; if (timeSinceSeen > 30 && (DateTime.Now - _lastSent).TotalSeconds > 15) { Ping(); } if (timeSinceSeen > 60) { // Client is gone _socket.Close(); _socket = null; _status = ConnStatus.Disconnected; } } } if (_pendingData != null) { byte[] packet = _pendingData.ToArray(); _pendingData = null; ProcessPacketData(packet); } }
private bool disposedValue = false; // 要检测冗余调用 protected virtual void Dispose(bool disposing) { this.Status = ConnStatus.Closed; if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象)。 CliDriver.Dispose(); this.Status = ConnStatus.Disposed; } // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 // TODO: 将大型字段设置为 null。 disposedValue = true; } }
/// <summary> /// Connects to the database. /// </summary> private bool Connect() { try { dataSource.Connect(); connStatus = ConnStatus.Normal; return(true); } catch (Exception ex) { connStatus = ConnStatus.Error; log.WriteException(ex, Localization.UseRussian ? "Ошибка при соединении с БД" : "Error connecting to DB"); Thread.Sleep(ErrorDelay); return(false); } }
public void OnDisconnect(FTAPI_Conn client, long errCode) { if (client is FTAPI_Qot) { lock (qotLock) { qotConnStatus = ConnStatus.DISCONNECT; return; } } if (client is FTAPI_Trd) { lock (trdLock) { trdConnStatus = ConnStatus.DISCONNECT; } } }
/// <summary> /// *The* background task for the shard. /// Executes service tasks and handles errors. /// </summary> private async Task WorkerLoop() { LastBackgroundRun = DateTimeOffset.UtcNow; try { while (!_workerCanceller.IsCancellationRequested) { await Task.Delay(Interval * 1000, _workerCanceller.Token).ConfigureAwait(false); // ConnectionStatus will always run. Its result determines if remaining tasks also this time. await ConnStatus.OnTick(_workerCanceller.Token).ConfigureAwait(false); if (!ConnStatus.Stable) { continue; } // Execute tasks sequentially foreach (var service in _workers) { try { await service.OnTick(_workerCanceller.Token).ConfigureAwait(false); } catch (Exception ex) { var svcname = service.GetType().Name; if (ex is TaskCanceledException) { Instance.Log(nameof(WorkerLoop), $"{svcname} was interrupted by a cancellation request."); throw; } else { // TODO webhook log Instance.Log(nameof(WorkerLoop), $"{svcname} encountered an exception:\n" + ex.ToString()); } } } LastBackgroundRun = DateTimeOffset.UtcNow; } } catch (TaskCanceledException) { } Instance.Log(nameof(WorkerLoop), "Background worker has concluded normally."); }
/// <summary> /// 解析接收的报文 /// </summary> /// <param name="buf">报文数据</param> /// <returns>是否向升级主站转发数据</returns> private bool ParsePacket(byte[] buf) { bool IsRetrunPacket = false; pType bufftype = cc.ParseData(buf); if (bufftype == pType.COMFIRM) { if (Login == ConnStatus.Logining) { Login = ConnStatus.logined; } else if (HeatBeat == ConnStatus.HeartBeating) { HeatBeat = ConnStatus.HeartBeated; } } else if (bufftype == pType.TRANSFER) { IsRetrunPacket = true; } return(IsRetrunPacket); }
public ConnStatus Open(Action <string> reciveOnlineData, string args = null) { _DataFrameManager = new DataFrameManager(); this.Status = ConnStatus.Opening; if (CliDriver == null) { CliDriver = Cli.Wrap(ConnectionStr, args); } this._DataFrameManager.Start(); CliDriver.ListenAsync(); CliDriver.SetStandardOutputCallback((msg) => { if (_DataFrameManager != null) { _DataFrameManager.Push(new DataFrameStr(msg)); } if (reciveOnlineData != null) { reciveOnlineData.Invoke(msg); } if (this.Status == ConnStatus.Opening) { this.Status = ConnStatus.Opened; this._ConnectionMREvent.Set(); } }); CliDriver.SetStandardErrorCallback((msg) => { // this.Dispose(); // throw new Exception(msg); }); CliDriver.SetStandardErrorClosedCallback(() => { this.Dispose(); }); _ConnectionMREvent.WaitOne(TimeSpan.FromSeconds(180)); return(this.Status); }
public void Start(AsyncCallback inConnCB, AsyncCallback outConnCB) { try { if (InPipe == null && OutPipe == null) { InPipe = new NamedPipeServerStream(s_InPipeName, PipeDirection.InOut, s_maxServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough, BUFFER_SIZE, BUFFER_SIZE, s_pipeSecurity); OutPipe = new NamedPipeServerStream(s_OutPipeName, PipeDirection.InOut, s_maxServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough, BUFFER_SIZE, BUFFER_SIZE, s_pipeSecurity); InPipe.BeginWaitForConnection(inConnCB, Id); OutPipe.BeginWaitForConnection(outConnCB, Id); Status = ConnStatus.Waiting; log.Info($"Named pipe id: {Id}, Start waiting for client connection."); } else { log.Warn("Try to Start pipe before stopping."); } } catch (Exception ex) { log.Error(ex); //throw ex; } }
public void SendPacket(SendPacketBase packet) { if (!_socket.Connected) { _conStatus = ConnStatus.Closed; return; } MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); packet.Write(_sequence++, bw); byte[] data = ms.ToArray(); LogInterface.Log(string.Format("Sent Packet to client ({0}) {1}: {2}", AccountID, packet.ToString(), data.Length), LogInterface.LogMessageType.Debug); LogInterface.Log(Utils.PrintBinaryData(data), LogInterface.LogMessageType.Debug); _scSec.EncryptInPlace(data); ms = new MemoryStream(); bw = new BinaryWriter(ms); bw.Write((ushort)data.Length); bw.Write(data); _socket.Send(ms.ToArray()); bw.Close(); }
//---------------------------------------------------------- // ConnectionStatusChanged handler //---------------------------------------------------------- public void OnConnStatus(ConnStatus connStatus) { //Show connect-status, and if connected show port we're using too AddResult(String.Format(" >Status: {0}{1}", connStatus.Status == eBTCONN_STATUS.BT_CONNECTION_COMPLETE ? "Connected" : connStatus.Status == eBTCONN_STATUS.BT_CONNECTION_LOST ? "Lost connection" : "Connection failed", connStatus.Status == eBTCONN_STATUS.BT_CONNECTION_COMPLETE ? "(" + connStatus.COMPort + ")" : "")); }
public Connection(Socket connectedSocket) { Init(); _socket = connectedSocket; _conStatus = ConnStatus.Connected; }
public void Update() { if (_socket != null) { if (!_socket.Connected && _status != ConnStatus.Disconnected) { _socket = null; _status = ConnStatus.Disconnected; } if (_socket.Connected) { // Read in packet data if (_socket.Available > 0) { _lastSeen = DateTime.Now; byte[] data = new byte[_socket.Available]; int bytesReceived = _socket.Receive(data); if (_pendingData != null) { _pendingData.AddRange(data); data = _pendingData.ToArray(); _pendingData = null; } ProcessPacketData(data); } // Are you still there? double timeSinceSeen = (DateTime.Now - _lastSeen).TotalSeconds; if (timeSinceSeen > 30 && (DateTime.Now - _lastSent).TotalSeconds > 15) { Ping(); } if (timeSinceSeen > 60) { // Client is gone _socket.Close(); _socket = null; _status = ConnStatus.Disconnected; } } } if (_pendingData != null) { byte[] packet = _pendingData.ToArray(); _pendingData = null; ProcessPacketData(packet); } }
public Connection(Socket connectedSocket) { Init(); _socket = connectedSocket; _conStatus = ConnStatus.Connected; }
public Connection() { Init(); _conStatus = ConnStatus.New; }
public void Close() { if( _socket != null ) _socket.Close(); _socket = null; _status = ConnStatus.Closed; }
public void Disconnect() { if (_socket != null && _socket.Connected) { _socket.Close(); } _conStatus = ConnStatus.Closed; }
public Connection() { Init(); _conStatus = ConnStatus.New; }
/// <summary> /// �������յı��� /// </summary> /// <param name="buf">��������</param> /// <returns>�Ƿ���������վת������</returns> private bool ParsePacket(byte[] buf) { bool IsRetrunPacket = false; pType bufftype = cc.ParseData(buf); if (bufftype == pType.COMFIRM) { if (Login == ConnStatus.Logining) { Login = ConnStatus.logined; } else if(HeatBeat == ConnStatus.HeartBeating) { HeatBeat = ConnStatus.HeartBeated; } } else if(bufftype == pType.TRANSFER) { IsRetrunPacket = true; } return IsRetrunPacket; }