public void Stop() { try { Started = false; ClientSessionDictionary nClientSessions = null; lock (_locker) { nClientSessions = ClientSessions.Clone() as ClientSessionDictionary; } foreach (var current in nClientSessions) { ClientSession state = current.Value; ushort client_id = current.Key; IStreamConnect connect = state.Connect; if (connect.IsDisconnected) { continue; } try { DisconnectSession(client_id); } catch (Exception e) { Console.WriteLine(e.StackTrace); } } lock (_locker) { ClientSessions.Clear(); } _listener.Close(); } catch { } }
/// <summary> /// 启动连接状态检查线程 /// 执行rtmp的读写异步任务 /// </summary> void ClientWorkHandler() { _clientWorkThread = new Thread(() => { while (true) { try { if (ClientSessions.Count() < 1) { Thread.Sleep(1); continue; } ClientSessionDictionary nclientSessions = null; lock (_locker) { nclientSessions = ClientSessions.Clone() as ClientSessionDictionary; } Parallel.ForEach(nclientSessions, current => { ClientSession state = current.Value; ushort client_id = current.Key; IStreamConnect connect = state.Connect; try { if (connect.IsDisconnected) { DisconnectSession(client_id); } else { if (state.WriterTask == null) { state.WriterTask = connect.WriteOnceAsync(); } else { if (state.WriterTask.IsCompleted) { state.WriterTask = connect.WriteOnceAsync(); } if (state.WriterTask.IsCanceled || state.WriterTask.IsFaulted) { this.DisconnectSession(current.Key); //throw state.WriterTask.Exception; } if (state.LastPing == null || DateTime.UtcNow - state.LastPing >= new TimeSpan(0, 0, _pingPeriod)) { connect.PingAsync(_pingTimeout); state.LastPing = DateTime.UtcNow; } if (state.ReaderTask == null || state.ReaderTask.IsCompleted) { state.ReaderTask = connect.ReadOnceAsync(); } if (state.ReaderTask.IsCanceled || state.ReaderTask.IsFaulted) { this.DisconnectSession(current.Key); //throw state.ReaderTask.Exception; } } } } catch { DisconnectSession(client_id); } }); } catch (Exception ex) { FleckLog.Error("ConnectStateCheckUp.Thread.Error", ex); } } }) { IsBackground = true }; _clientWorkThread.Start(); }