using Infrastructure.Extensions; using Microsoft.AspNetCore.Hosting; using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace IoTNode.DeviceServices.LiChuang { public class LCDAUE800DService : BaseDeviceService { private TcpListener _listener; private CancellationToken _cancellationToken; public LCDAUE800DService(IServiceProvider applicationServices, IWebHostEnvironment env) : base(applicationServices, env) { } public override Task StartAsync(CancellationToken cancellationToken) { this._env.Debug("~~start"); this._cancellationToken = cancellationToken; return base.StartAsync(cancellationToken); } public override void Execute() { this._env.Debug("lc exec"); try { if (this._listener == null) { this._listener = new TcpListener(IPAddress.Any, 7000); this._listener.Start(); Task.Run(() => { try { while (!this._cancellationToken.IsCancellationRequested) { var client = _listener.AcceptTcpClient(); Task.Run(() => { new ClientWraper(_applicationServices, this, client).Run(); }); } } catch (Exception ex) { ex.PrintStack(); } }); } } catch (Exception ex) { this._listener = null; ex.PrintStack(); } } public override Task StopAsync(CancellationToken cancellationToken) { this._env.Debug("lc end"); return base.StopAsync(cancellationToken); } } }