using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using WIDESEAWCS_QuartzJob; namespace WIDESEAWCS_Tasks.SocketServer { /// /// TCP Socket·þÎñ¶Ë£¨»ùÓÚÐÐЭÒ飬°´»»Ðзû·Ö¸îÏûÏ¢£© /// public partial class TcpSocketServer : IDisposable { private readonly SocketServerOptions _options; public readonly object _syncRoot = new(); private TcpListener? _listener; public CancellationTokenSource? _cts; public readonly List _clientTasks = new(); public readonly Dictionary _clients = new(); public readonly Dictionary _deviceBindings = new(); public readonly Dictionary _clientLocks = new(); public readonly Dictionary _clientEncodings = new(); public readonly Dictionary _clientLastActive = new(); public readonly Encoding _textEncoding; public readonly Encoding? _autoDetectedGb2312; private readonly string _logFile; private Task? _monitorTask; public TcpSocketServer(IOptions options) { _options = options.Value; if (_options.AutoDetectEncoding) { _textEncoding = Encoding.UTF8; try { _autoDetectedGb2312 = Encoding.GetEncoding("GBK"); } catch { _autoDetectedGb2312 = null; } } else { try { _textEncoding = Encoding.GetEncoding(_options.EncodingName ?? "utf-8"); } catch { _textEncoding = Encoding.UTF8; } _autoDetectedGb2312 = null; } _logFile = Path.Combine(AppContext.BaseDirectory ?? ".", _options.LogFilePath ?? "socketserver.log"); Log($"[{DateTime.Now}] TcpSocketServer starting"); } public bool IsRunning { get; private set; } public event Func>? MessageReceived; public event Func>? RobotReceived; private void Log(string message) { Console.WriteLine(message); try { File.AppendAllText(_logFile, message + Environment.NewLine); } catch { } } } }